• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Java: Class.forName()

JonTheBaller

Golden Member
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.
 
Class.forName() is used to give you a handle to a Class.

From there you can use reflection to call the appropriate constructor.
 
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();
 
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.
 
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();
 
Back
Top