Anupam Jain
Anupam Jain

Reputation: 101

Determine which fields of a POJO are being accessed in a code

I have a huge (parent) POJO which is being used in some component. The POJO has individual fields as well as nested POJOs as well. Is it possible to determine what all fields/ nested fields from this POJO are being accessed in that component?

I was thinking about JUnits/ aspects but not sure if either would work. I've tried looking through SF/ and Google but could not find any relevant thread for this thing.

Say following is a sample POJO:

public class Student {

  private String name;
  private Date date;
  private Subject subject;

  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public Date getDate() {
    return date;
  }
  public void setDate(Date date) {
    this.date = date;
  }
  public Subject getSubject() {
    return subject;
  }
  public void setSubject(Subject subject) {
    this.subject = subject;
  }

}

It has three fields name, date and subject, not all of which would be in use in my component. So I need to determine which are actually being used.

Edit: Thanks Sharon for pointing out that the getter/setters were protected. I had just generated the class on the fly for the purpose of question and didn't notice the issue. Corrected now. How the class is initialised: For the purpose of the component, objects will be created from Json/XML data and would have only getters being called. As for static vs runtime analysis, I'd prefer to achieve it through static code analysis if that's possible otherwise runtime also is fine with me if that's easier. As for using Decorator pattern, do we have anything without requiring existing code change? That's why I was thinking if JUnits could do this.

Upvotes: 2

Views: 170

Answers (1)

Sharon Ben Asher
Sharon Ben Asher

Reputation: 14383

First of all, it is odd to see getter/setter methods that are protected. seems to me they need to be public?
Anyway, I would utilize the Decorator design pattern. From the linked article:

The decorator design pattern allows us to dynamically add functionality and behavior to an object without affecting the behavior of other existing objects in the same class.

So, our decorated Student should inherit from the target class. All methods can log their usage and call super to invoke target operation. You didn't say how Student is initialized, but anyway, you will want to modify that to create instances of LogUsageStudent

public class LogUsageStudent extends Student {

  protected String getName() {
    // log usage of getName() 
    return super.getName();
  }
  // etc
}

Upvotes: 1

Related Questions