开发者

Java+Reflection: Invoke method on variable access. Is it possible?

I was wondering if it is possible, usi开发者_高级运维ng reflection, or something similar to invoke a method whenever a variable is accessed in read or write mode. In a nutshell my goal is similar to the behavior of C# properties.

Example: Let's say I have a two classes A and B...

public class A{
    public int field;

    public void foo(){ System.out.println("Field modified");}
}

public class B{
    public void bar(A a){
        a.field = 1;
    }
}

...and I want to execute the method A.foo() whenever a.field is written.

Is this achieveable in Java?

Thanks in advance

p.s. I'm aware that good programming practices suggest to use getter and setter. I just need to know if what I want to do is feasible.

ac


Not via reflection - reflection simply lets you get access to static information about classes/fields/etc at runtime.

Aspect oriented programming is more what you're thinking of - this lets you inject small bits of code (called "advice") at certain points of your source code (such as before a method runs, when a field is set, etc.). This would almost certainly let you do what you are looking for.

A word of warning though - as you seemed to pick up, it's unlikely to be a good idea to rely on aspects for your general logic as it's very hard to reason with them, and work out exactly what will happen when (by definition, they break the default mental model that calling a method foo() means that control passes directly to that method). AOP is great for things like logging or debugging though, as it lets you write small bits of code that affect a lot of cross-cutting concerns with little effort, and don't require you to modify the code of the underlying application. Your advice can be weaved in as required, and simply left out when not required.


I was wondering if it is possible, using reflection, or something similar to invoke a method whenever a variable is accessed in read or write mode.

Yes. If you properly encapsulate your data using getter and setter methods, you could put such code in these methods, or, override these methods in a subclass.

(now I saw your ps) - No, there is no way of solving this using reflection. If I was asked (forced?) to solve this problem, I would write my own class loader, perhaps using the ASM framework, and replace each get-field/set-field instructions with proper calls to getter/setter methods.

They actually have a FAQ-entry for this, with a solution:

  • 9. How do I generate Setters and Getters for my class?


AFAIK, you can't do it in Java. As you said, use getters and setters.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜