Reputation: 121
My question is, is it possible to inject properties or even methods into a already "classloaded" class. I already noticed, that in java it is not really simple to add properties dynamically and everyone says that you should use a Map (add property for a object dynamicly).
Is there any better and "cleaner" way to change a class during runtime. I read something about ASM, but i do not know if the visitor pattern, which is use by ASM, is the optimal way to work with.
In case ASM is the best thing to handle this problem, is there any documentation beside the one provided on the ASM Website (http://download.forge.objectweb.org/asm/asm4-guide.pdf)
Upvotes: 1
Views: 1801
Reputation: 718708
Once a class has been loaded by the JVM, it is not possible to modify it.
Your best bet is to modify the class, then load a fresh copy ... in a different classloader. You will end up with two versions of the class (with different runtime types!). Any instances of the first version of the class will not have the new fields, methods etcetera.
My advice ... don't do it. Think of another way to implement what you are actually trying to do here. Or if modifying classes on the fly is fundamental to your application, consider using a more dynamic language.
Upvotes: 2