Java: Class.forName()

JonTheBaller

Golden Member
Dec 2, 2002
1,916
0
0
Can someone give me a good explanation of how to use Class.forName()? I need to be able to make an object of any arbitrary class.
 

m0ti

Senior member
Jul 6, 2001
975
0
0
Class.forName() is used to give you a handle to a Class.

From there you can use reflection to call the appropriate constructor.
 

JonTheBaller

Golden Member
Dec 2, 2002
1,916
0
0
Originally posted by: m0ti
Class.forName() is used to give you a handle to a Class.

From there you can use reflection to call the appropriate constructor.

I'm not familiar with reflection.

Is there anyway I can just write

Class c = Class.forString( "className" );
Object o = new c();
 

m0ti

Senior member
Jul 6, 2001
975
0
0
no more like:

Class c = Class.forName("SomeClassName");
Object o = c.newInstance();
 

JonTheBaller

Golden Member
Dec 2, 2002
1,916
0
0
Actually one more question, when I refer to the Object, do I need to cast it?

If I know all my classes have a print() method, would I just say

o.print();

?

Thanks again.
 

m0ti

Senior member
Jul 6, 2001
975
0
0
Yes, you do have to cast it.

Your best bet for these things is to create an interface with all the common methods there and have your objects extend them. Then you can do a cast to that interface.

So you could do:

Printable p = (Printable)Class.forName("SomeClass").newInstance();