0

I have a class Person and I'd like to be aware of every call to getFirstName() method:

public class Person {
   private String firstName;
   private String lastName;

   public Person() {...}

   public String getFirstName() {
      return this.firstName
   }

   //... Rest of getters and setters
}

So when somebody does this, I'd like to print out "Hello world" for example (actual use would be more complicated):

public class Main {

   public static void main(String[] args) {
      Person person = new Person("John", "Doe");
      person.getFirstName();
   }

However I want to do this without modifying Person class (at least NOT before compilation). I read sth about Observable pattern and Property Change Listeners, but they don't seem to be doing what I'd want. Is such thing even possible in java ?

3
  • You're trying to make a class behave as if it were observable, but without giving it the wiring to allow this to be so (your "Person cannot be modified" requirement). As I see it you have two options: 1) Change your requirements so that Person is in fact wired to be observed, or 2) Give up on this Commented Apr 13, 2019 at 13:05
  • Edit: I was wrong, as there is a way using an aspect-oriented library or approach. Other similar questions on this site Commented Apr 13, 2019 at 13:08
  • @HovercraftFullOfEels I've seen this one, but what if i want to listen to more than just one method or even more than one class. Commented Apr 13, 2019 at 13:16

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.