| Author |
how to create object of a class whose name is contained in a string
|
Rajiv Chelsea
Ranch Hand
Joined: Jun 15, 2010
Posts: 88
|
|
Hi
lets suppose
String className = com.rajiv.SomeClass
How can i make an object of SomeClass?
|
 |
Matthew Brown
Bartender
Joined: Apr 06, 2010
Posts: 3793
|
|
|
Check out the methods of the java.lang.Class class. (In particular, you want to look at forName() and newInstance()). That should give you what you want.
|
 |
Wouter Oet
Saloon Keeper
Joined: Oct 25, 2008
Posts: 2700
|
|
|
Since this is the beginning Java section I want to ask you this: why do you want this? Because reflection (which you're going to use with the Class methods) is not a beginning Java topic and you lose a lot of advantages that you have with regular Java.
|
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
|
 |
Rajiv Chelsea
Ranch Hand
Joined: Jun 15, 2010
Posts: 88
|
|
I can do the following
Class.forName(className).newInstance();
but the above line of code returns an object
How do i recast it to SomeClass which is the original class name.
|
 |
Paul Beckett
Ranch Hand
Joined: Jun 14, 2008
Posts: 95
|
|
You may need to think a little bit about what you are asking. If you are reading a class name from a String and you don't know what the class is until runtime then what are you going to cast it to?
However if you have a class hierarchy such as:
class Shape{}
class Circle extends Shape{}
class Square extends Shape{}
and you *always* read the subclass of Shape then you can cast to the Shape superclass. If you can complete all the logic you need via a variable of type Shape then fine. If not you may need to use a conditional block that checks which subtype of Shape your instanceof is and then casts to the appropriate subtype.
|
 |
 |
|
|
subject: how to create object of a class whose name is contained in a string
|
|
|