views:

199

answers:

2

Hi everyone, 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

+1  A: 

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.

bkail
A: 

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 ?

Romain Hippeau