Skip to main content
GameDev.net gamedev.net
🔒 Locked

[java] Add a data member to a Java class at runtime?

Started by crivens May 2, 2009 at 7:15 PM 4 replies 2.8k views
Original Post
crivens
crivens
Is it possible to add a data member to a Java class at runtime? I've been reading up on reflection but I've not found the answer yet. Thanks
stonemetal
stonemetal
Yes you can swap out a class for another one while an app is running it is called hotswap. Note it is more of a debugging technique than a thing you would actually want to do regularly at runtime.
crivens
crivens
Thanks!
Zahlman
Zahlman
You can replace a class at runtime, but you can't really modify the implementation of existing classes (including what fields they contain).

However, you don't really need to "add fields at runtime" in order to get the effect of adding named data to a class at runtime. Just use, for example, java.util.Hashtable, and add a key-value pair to the table. Calling code will refer to the data with a String instead of a variable name.
FlaiseSaffron
FlaiseSaffron
If you are dynamically adding fields to a class, the only way to access them is by dynamically changing the classes that would need to use them, which is far more work and probably much less efficient than using a collection designed for the purpose. So yeah, use a Hashtable (or HashMap if your code is single-threaded).
polly
polly
I think you should take a look at Groovy - a language for the JVM. Depending on exactly what you're trying to do, you may find that "Closures" in Groovy give you what you need.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.