vendredi 22 juin 2018

Is it possible to execute code before a field is accessed in java?

I am trying to automate the construction of some objects in java.

To do this, I have these sample classes:

class TestInjected extends CommonAncestor {

  TestInjected() {
    System.out.println("I am Test Injected");
  }

  void exist() {
    System.out.println("Hey there, I exist");
  }

}

class CommonAncestor {

  CommonAncestor() {
    super();
    init();
  }

  void init() {
    try {
        Field f = this.getClass().getDeclaredField("x");
        f.set(this, f.getType().newInstance());
    } catch (NoSuchFieldException e) {
    } catch (IllegalAccessException e) {
    } catch (InstantiationException e) {
    }
  }

}

public class TestInjection extends CommonAncestor{
  TestInjected x;
  private TestInjected y;

  private TestInjected getY() {
    if (y == null) {
      y = new TestInjected();
    }
    return y;
  }

  public TestInjection() {
    super();
  }

  public void test() {
    x.exist();
  }

  public void test2() {
    getY().exist();
  }

}

And I also have a testing class:

public class TestInjectionTest {

  @Test
  public void test1() {
    TestInjection t = new TestInjection();
    t.test();
    t.test2();
  }
}

What I am doing here is, on constructor, I check for the Field x, and I initialize it via reflection. This way, I make sure that whenever a method is called, like in this case, test(), Field x has already been initialized, and therefor, it works.

The second approach, is to force programmers to use a getter, in this case, for Field y, where this getter method makes sure to initialize the object.

However, I am wondering, if hava has any way to execute reflection, when a variable is accessed. Let's say, instead of having to execute reflection code on constructor, if somehow, that code could be executed whenever "x" is required.

i.e:

x.exist()

--> check x is getting called, initialize it, and then call exist()

Any reflection method, or any library, that gives me this?





Aucun commentaire:

Enregistrer un commentaire