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

Started by
4 comments, last by polly 14 years, 11 months ago
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
Advertisement
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.
Thanks!
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.
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).
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.

This topic is closed to new replies.

Advertisement