1

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)

asked Apr 8, 2017 at 0:05
6
  • What would be the use-case for this? Commented 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 things Commented Apr 8, 2017 at 1:12
  • 1
    As 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. Commented 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? Commented Apr 8, 2017 at 2:16
  • 1
    Found the talk: vimeo.com/138954121 "JRebel under the covers - how is it even possible? - Simon Maple" Commented Apr 8, 2017 at 2:30

1 Answer 1

2

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.

answered Apr 8, 2017 at 3:11
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.