1
1
|
In Java, is it possible to override methods in a class that you create using
reflection ? For example, say I have the following class:
And in one class I want to create it directly and override its
setBar method as follows:
Is there a way to override a method in this same manner using reflection? Maybe something like this? :
If not, are there other ways of doing this, or an external library that could help? I am looking for way to add listeners to a setter method in order to change binded values.
| ||||
|
2
|
No, it's not possible in the way of your example.
In your example, the Java compiler will create two separate classes:
The latter being the one with the overridden method. In this case, it's an anonymous inner class (SeeJava tutorial documentation)
But there is more complex solution involving bytecode weaving libraries. Libraries such as cglib, asm, javassist etc. give you a facility to dynamically create new classes at runtime and load them.
Javassist has a tutorial on how to add methods to classes at runtime. It should be possible to adapt it to add/override the method, something like this:
| ||