Solved

How to add a new data member at runtime?

Posted on 2010-08-31
15
492 Views
Last Modified: 2013-12-29
Hello,
Is it possible to add a field (a data member) into a class at runtime? I could not find anything in reflection to do this in Java.

Thanks
prain
0
Comment
Question by:prain
  • 4
  • 3
  • 2
  • +4
15 Comments
 
LVL 2

Expert Comment

by:arch-itect
Comment Utility
You do get java class file editors (see Google)

you also get bytecode libraries like

http://asm.ow2.org/

but I think what you are looking for is a Hashtable or HashMap where you can add name value pairs at runtime.

Hashtable<String, Object>() vehicles = new Hashtable<String, Object>();
myValues.put("car", new Car());

0
 

Author Comment

by:prain
Comment Utility
OK. Let me give an example to explain what I am loking for. if I have a class

public class Person
{
   private String name;
   private int  age;
}

Is it possible for me to add a member

  private String Address;

info the class during runtime. So at runtime, the 'class' would like


public class Person
{
   private String name;
   private int  age;
   
   private String Address;
}

Thanks
prain
0
 
LVL 26

Expert Comment

by:ksivananth
Comment Utility
you can achieve this with haspmap as said earlier!
0
 
LVL 4

Expert Comment

by:aaver
Comment Utility
As already said, this is probably possible to do in a much simpler way.
Could you explain why you cannot use a hashmap to hold different data?
0
 
LVL 4

Assisted Solution

by:aaver
aaver earned 41 total points
Comment Utility
If you really need a truly dynamic approach, you might consider javax.tools.JavaCompiler.

This is a good example of doing that:
http://www.ibm.com/developerworks/java/library/j-jcomp/index.html
0
 
LVL 10

Expert Comment

by:Hegemon
Comment Utility
If you need to add properties only once and need to getters/setters for it, you can generate a subclass with the necessary properties using any of available "code enhancements" libraries. For example, using the BeanGenerator library you can generate a runtime class extending your Person class and containing the "extra" properties. Something like:

        BeanGenerator bg = new BeanGenerator();
        bg.setClassLoader(cl);
        bg.setSuperClass (Person.class);
        bg.addProperty ("address", String.class);
        ...
        Class generatedPersonExt = bg.createClass();
0
 
LVL 16

Accepted Solution

by:
Valeri earned 43 total points
Comment Utility
You can not do that.
In my opinion If you need this, it means that there is something wrong in your design.
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:prain
Comment Utility
Hegemon,

Is the BeanGenerator part of J2SE? and what is 'cl' in line 2 of your code sample?

prain
0
 
LVL 2

Expert Comment

by:arch-itect
Comment Utility
You either have to generate and compile the code at runtime (which is possible)
or you can do that with javascript inside java (although not in the way you suggest)

http://www.mozilla.org/rhino/

It is like you are trying to write a language, or interpreter in java.  I can explain to you how javascript does it, enable you to create "classes" at runtime, and it involves HashMaps.
0
 
LVL 10

Assisted Solution

by:Hegemon
Hegemon earned 41 total points
Comment Utility
BeanGenerator is a part of the cglib library: http://cglib.sourceforge.net/
cl is a ClassLoader object that you can obtain using Person.class.getClassLoader();

BTW, apart from cglib, there is another well known code instrumentation library - javassist: http://en.wikipedia.org/wiki/Javassist

In my example I used BeanGenerator as in my view it is the simplest way to achive the goal.
0
 

Author Comment

by:prain
Comment Utility
I have a problem getting these non core-jave libraries. This is the problem when you work for the government. I cannot just download someone else's libraries without prior permission - which might take several weeks to approve. :-)

Your solution looks a viable solution to my issue. Unfortunately I cannot test it out because of the library issue.

-prain
0
 
LVL 10

Expert Comment

by:Hegemon
Comment Utility
Do you use Hibernate ? cglib and javassist are shipped with it.
0
 

Author Comment

by:prain
Comment Utility
Yes we do use Hybernate. Let me see, and will get back. Thanks. prain
0
 
LVL 26

Expert Comment

by:mrcoffee365
Comment Utility
This question has been classified as abandoned and is closed as part of the Cleanup Program. See the recommendation for more details.
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
copyEndy  challenge 15 55
triangle challenge 4 75
for i loop in grovy 1 32
Starting to learn JAVA, 7 47
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
The viewer will learn how to implement Singleton Design Pattern in Java.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now