Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to...String to class

 
Django Boonman
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How can i instantiate a class when all i've got is a String?
Say i have "Person", how can i instantiate an object Person?
Class myClass = Class.forName("Person");
Constructor ctor = myClass.getConstructor( new Class[ ] { } );
Object myObj = ctor.newInstance( new Object[ ] { } );
myObj is now of type Object, how can i make that type Person???
 
Frank Carver
Sheriff
Posts: 6920
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are almost there.
Heres a modified version of the code I use:
 
Django Boonman
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Slight correction, I think it should be:
if ( personClass.isInstance(personObject) ) {
person = (Person)personObject;
}
However I was more looking for a dynamically StringToType kind of function. Eg when i only read a string "DONTKNOWWHATTYPE",
how can i make an object of type DONTKNOWWHATTYPE.
Casting is not an option because I don't know to what type to cast, I only have the string, not the type.
I don't want to declare on forehand all the objects i am going to read.
<Person> myObj = new <Person>( );
Not an easy one from the greenhorn, btw Thanx
 
Carl Trusiak
Sheriff
Posts: 3341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a perfect place for an abstract class and inheratance.
First you create your parent class which all classes that you wish to use must inherate from
public abstract class Pet
{
public abstract init();
}
public Dog extends Pet
{
public init()
{
...whatever
}
}
Then your controlling program only has to be
try
{
Class pet = Class.forName(name);
Object animal = pet.newInstance();
if (animal instanceof Pet) {
usePet = (Pet)animal;
}
else
{
System.out.println("class '" + classname + "' ignored - not a Pet");
}
}
catch(ClassNotFoundException e)
...
usePet.init();
 
madhesh raj
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Your suggestion works only if we have a predefined set of classes against which we can compare.
But, consider the classic case of a Javaeditor capable of compiling and running a Java program. It needs to select a class file at runtime and execute the same. We will get the classname as a string from the frontend. Since, there maybe any no. of classes, how do we invoke the correct method. It is needless to say that they cannot have a single abstract class as a common parent
Madhesh
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic