Sign in to follow this  
crivens

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

Recommended Posts

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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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).

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this