Matt Gerrans
Posts: 1153
Nickname: matt
Registered: Feb, 2002
|
|
Re: How to make an instance of a class from a string?
|
Posted: Mar 9, 2002 10:35 PM
|
|
I'm not sure if I correctly understand your qustion, in the context of the code you are including, but here is some code to demonstrate how you instantiate an object based upon its name:
public class ForName
{
public static void main(String [] args)
{
Object ob = null;
try
{
ob = Class.forName(args[0]).newInstance();
System.out.println( "Instantiated an object called \"" + ob.getClass().getName() +
"\", it's toString() gives: " + ob.toString() );
}
catch(ArrayIndexOutOfBoundsException aioobe)
{
System.out.println( "Specify the name of the class you want to instantiate!" );
}
catch(ClassNotFoundException cnfe)
{
System.out.println( "Can't find a class called \"" + args[0] + "\", try one that exists!" );
}
catch(InstantiationException ie)
{
System.out.println( "Failed to instantiate class \"" + args[0] + "\", try another!" );
}
catch(IllegalAccessException iae)
{
System.out.println( "Sorry, pal, you are not allowed to instantiate a \"" + args[0] + "\", try another!" );
}
}
}
class TestClass
{
public TestClass()
{
System.out.println( "Created a " + this.getClass().getName() );
}
public String toString()
{
return "I'm a TestClass object!";
}
}
class AnotherTestClass
{
public AnotherTestClass()
{
System.out.println( "Created a " + this.getClass().getName() );
}
public String toString()
{
return "I'm a AnotherTestClass object!";
}
}
You can experiment with it by running it with any class name (fully qualified) that you can think of. Here are some examples:
C:\temp>java ForName java.util.ArrayList Instantiated an object called java.util.ArrayList, it's toString() gives: []
C:\temp>java ForName java.util.ArrayList Instantiated an object called "java.util.ArrayList", it's toString() gives: []
C:\temp>java ForName TestClass Created a TestClass Instantiated an object called "TestClass", it's toString() gives: I'm a TestClass object!
C:\temp>java ForName java.security.spec.X509EncodedKeySpec Failed to instantiate class "java.security.spec.X509EncodedKeySpec", try another!
C:\temp>java ForName java.util.Random Instantiated an object called "java.util.Random", it's toString() gives: java.util.Random@3e86d0
Note that it can fail to create classes for a number of reasons: if it is abstract, an interface, doesn't have a default constructor, or has a private one, etc.
You may want to add more detail to the exception handling, if you want to understand better why a particular class fails to be instantiated.
|
|