Interception of access to fields and methods of Java, creation of proxy objects

I want to create such an object in Java that will contain some "dispatcher" function, such as Object getAttr(String name)one that will receive all attempts to access the attribute - so if I do System.out.print(myObj.hello), the actual code will be translated into something like System.out.print(myObj.getAttr('hello')), and if I I will myObj.hello = 123, it should be executed as myObj.setAttr('hello', 123). Please note that I must use ANY attribute name, I do not know the list of possible names in advance.

So is this possible in this case?

UPD # 1: I am writing a new language for the JVM (somehow (J | P) ython-like, so let me call Jython) with very complicated Java integration. One of the necessary design features is the ability to freely access the attributes of a Jython object from Java code by simply typing jythonObject.some_attribute. So here is the deal.

Closed: Using AOP through AspectJ seems to be the only possible solution for this, so thank you all for your help, and especially Thomas for the most advanced answer :)

+3
source share
5 answers

It is impossible to use pure Java, except through:

Byte Code Manipulation

For example, using AspectJ.

Annotation handler

, -. Projekt Lombok - .

, ( ):

public class Test {
    public static void main(String... args) {
        TestClass t = new TestClass();
        // this is actually calling a synthetic accessor method
        t.hello = "x";
    }
    static class TestClass {
        private String hello;
    }
}
+3

, . get/set.

. ( : , .)

(, , , , ), , - -.

, , .

+2

You will need to use AspectJ (http://www.eclipse.org/aspectj/) or another AOP library.

+1
source

Groovy The language has tools for AOP, and a tiny library already exists to handle your case: https://github.com/nanonull/bean-trace

0
source

All Articles