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)
-
What would be the use-case for this?Oliver Charlesworth– Oliver Charlesworth2017年04月08日 01:03:46 +00:00Commented Apr 8, 2017 at 1:03
-
I was pretty impressed by spring & co and I thought why do not try to code something same, just to learn more about java.reflection and the process which could be behind such a great framework. Short: I want to learn new thingsDiego Krupitza– Diego Krupitza2017年04月08日 01:12:22 +00:00Commented Apr 8, 2017 at 1:12
-
1As far as I remember from a talk by someone from ZeroTurnaround (who makes JRebel) adding fields and methods to existing classes is really hard and requires workarounds like actually swapping the entire class with a new one and then updating all links to the class. Trying to find the talk online, will update if I do.Erik Vesteraas– Erik Vesteraas2017年04月08日 02:15:09 +00:00Commented Apr 8, 2017 at 2:15
-
And just to be clear, updating existing fields is not that hard, but I assume that is not what you are asking about?Erik Vesteraas– Erik Vesteraas2017年04月08日 02:16:50 +00:00Commented Apr 8, 2017 at 2:16
-
1Found the talk: vimeo.com/138954121 "JRebel under the covers - how is it even possible? - Simon Maple"Erik Vesteraas– Erik Vesteraas2017年04月08日 02:30:37 +00:00Commented Apr 8, 2017 at 2:30
1 Answer 1
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.