Solved

How to add a new data member at runtime?

Posted on 2010-08-31
15
495 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
ID: 33572127
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
ID: 33573372
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
ID: 33574049
you can achieve this with haspmap as said earlier!
0
 
LVL 4

Expert Comment

by:aaver
ID: 33574436
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
ID: 33574546
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
ID: 33575057
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
ID: 33575644
You can not do that.
In my opinion If you need this, it means that there is something wrong in your design.
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:prain
ID: 33576197
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
ID: 33576198
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
ID: 33576687
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
ID: 33578213
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
ID: 33578234
Do you use Hibernate ? cglib and javassist are shipped with it.
0
 

Author Comment

by:prain
ID: 33578548
Yes we do use Hybernate. Let me see, and will get back. Thanks. prain
0
 
LVL 27

Expert Comment

by:mrcoffee365
ID: 37126756
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Java Message handling in Service Layer 3 55
Securing Jmx Console and web console 2 64
JList custom Cell Renderer refresh 15 53
map related example 6 29
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
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…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

930 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

13 Experts available now in Live!

Get 1:1 Help Now