File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes How to...String to class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "How to...String to class" Watch "How to...String to class" New topic

How to...String to class

Django Boonman

Joined: Mar 08, 2000
Posts: 10
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

Joined: Jan 07, 1999
Posts: 6920
You are almost there.
Heres a modified version of the code I use:

Read about me at ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
Django Boonman

Joined: Mar 08, 2000
Posts: 10
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

Joined: Jun 13, 2000
Posts: 3340
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()
Then your controlling program only has to be
Class pet = Class.forName(name);
Object animal = pet.newInstance();
if (animal instanceof Pet) {
usePet = (Pet)animal;
System.out.println("class '" + classname + "' ignored - not a Pet");
catch(ClassNotFoundException e)

I Hope This Helps
Carl Trusiak, SCJP2, SCWCD
madhesh raj
Ranch Hand

Joined: Nov 28, 2000
Posts: 62
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
I agree. Here's the link:
subject: How to...String to class
It's not a secret anymore!