This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Java in General and the fly likes Making an object from a String variables value Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Making an object from a String variables value" Watch "Making an object from a String variables value" New topic
Author

Making an object from a String variables value

Roshan Khandelwal
Ranch Hand

Joined: Apr 16, 2009
Posts: 35
Say I have a string.. which obtains the name of a class after parsing an XML file....
Now i need to make an object of that particular class.. to set data in it.

However the class name is stored as the string variable value .
Is it possible to use it to make an instance of that class...

Example :



Now i want to make an object of type Test1....but using the value of string only.. Is it possible
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18757
    
  40

Take a look at the Java Reflection classes.... java.lang.Class and the classes in the java.lang.reflect.* package.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Roshan Khandelwal
Ranch Hand

Joined: Apr 16, 2009
Posts: 35
@Henry : Can you please give an example??
or maybe direct me to appropriate websires.. though i am trying it myself..
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18757
    
  40

Roshan Khandelwal wrote:@Henry : Can you please give an example??
or maybe direct me to appropriate websires.. though i am trying it myself..



Just google for "java reflection". There are a few tutorials about it.

Or you can take a look at the two java classes in the JavaDoc that you will need -- java.lang.Class and java.lang.reflect.Constructor. Although, I recommend learning about the whole library than just two classes.

Henry
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Making an object from a String variables value