aspose file tools*
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
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: 18120
    
  39

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: 18120
    
  39

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
 
wood burning stoves
 
subject: Making an object from a String variables value
 
Similar Threads
Call method from method dynamic
String Doubt
I am getting clone() has protected access in java.lang.Object
Regarding Polymorphism
find creator of an object