开发者

Change field access to getter / setter method access

is it possible to change external class 开发者_如何学运维field accesses in Java to getter / setter calls automatically, and also hide the exposed fields? I'm using Javabeans and I want change notifications when a field property changes (this is important).

I've found cglib which can automatically insert the property change call to the PropertyChangeSupport field. I know about Project Lombok, but this appears to modify the source code, and additionally doesn't support field access modification. Perhaps with modifications to Lombok, this could be supported, or are there other solutions?

Cheers and thanks in advance, Chris


The easiest option would be to modify the source of the API clients. Assuming that's not an option, there's no way to automatically encapsulate fields in this way unless you at least have control over the client binaries and can use bytecode manipulation. If you have that level of control, then yes, cglib might be an option. However, even with bytecode manipulation, there is no way to intercept java.lang.reflect.Field.set, so you would need to guarantee that nothing modifies the fields using reflection.

Your best option is to break the API and introduce setters/getters. This should be a reminder to always use proper encapsulation when creating an API.


AspectJ will allow you to do the notification piece. You can do some runtime weaving of the classes and then detect when somebody changes an instance variable or calls a method and then take whatever action you want.
It is not for the timid !!!

Not sure what you mean by changing the access without changing the code ?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜