Home > Net >  Figure out If a session object field has been accessed
Figure out If a session object field has been accessed

Time:12-16

I have a java object, say House, which gets stored in session and gets retrieved by a number of methods. This House object has a String field called streetAddress. Say method1 is a method that retrieves this object from the session and that possibly accesses the streetAddress field.

By accesses I mean even a simple read of this field like house.getStreetAddress() != null.

I'm now in method2, I retrieve the House object from session and I would like to know if the streetAddress field has ever been accessed. This field is private, so the only ways to interact with it outside the class are the getter and setter methods. Is it possible to know if either one of these two methods has ever been called during this session?

I've looked into java reflection but didn't find anything useful.

CodePudding user response:

This is exactly why we write getters and setters rather than directly accessing fields. Your getter can take logs internally, and it doesn't affect users of your API. Consider

public class House {
  private String streetAddress;
  private boolean streetAddressAccessed;

  public House(String streetAddress) {
    this.streetAddress = streetAddress;
    this.streetAddressAccessed = false;
  }

  public String getStreetAddress() {
    // Somebody called this function; make a note!
    streetAddressAccessed = true;
    return streetAddress;
  }

  public boolean wasStreetAddressAccessed() {
    return streetAddressAccessed;
  }

}

CodePudding user response:

You either have to write a proxy by which you access the House object that counts the method calls and provides them somehow, or you prepare the implementation of House itself to record calls to it's methods.

Another possibility would be the use of a so called "profiler" that measures the time that is spent in called methods. This is more something for the occasional use, e.g. when you are searching for performance bottlenecks.

You could use VisualVM that contains a very simple profiler that can connect to an already running JVM - https://visualvm.github.io/

  •  Tags:  
  • java
  • Related