[3632] in java-interest

home help back first fref pref prev next nref lref last post

Re: Dynamic Object Instantiation ....

daemon@ATHENA.MIT.EDU (Gary Aitken)
Mon Nov 20 19:20:17 1995

Date: Mon, 20 Nov 1995 00:54:11 -0700
From: garya@village.org (Gary Aitken)
To: neudeck.arthur@ch.swissbank.com, java-interest@java.sun.com
Cc: neudeca@ch.swissbank.com
In-Reply-To: <9511171042.AA16383@foxy.ch.swissbank.com>

>I load a new class by a given name from a directory.
>Afterwards I instantiate a new Object that way:
>Object newObject	= Class.forName("...")
>
>Everything works fine until the moment I try to call a method of this new
>object. I do have the problem, that the Class object does not provide the
>called method, e.g.:
>newObject.getOID();
>
>How can I instantiate the object with the right cast???

This isn't what you want; the above only gives you the class descriptor
for the type of object you want, not an object of that type.
To get an object of the proper type, you need to use the newInstance
method from the class description returned.  You'll need to catch
all the relevant exceptions:

public class CloneTest {
	public static void main( String argv[] ) {
		Class	cls;		// Class description for desired class
		String	str;		// new object

		try {
			cls = Class.forName( "java.lang.String" );
			try {
				str = (String) cls.newInstance();
				System.out.println( str.length() );
				System.out.println( str );
			}
			catch ( java.lang.IllegalAccessException ex) {
				System.out.println( "IllegalAccessException" );
			}
			catch ( java.lang.InstantiationException ex) {
				System.out.println( "InstantiationException" );
			}
		}
		catch ( java.lang.ClassNotFoundException ex ) {
			System.out.println( "Class not found" );
		}
	}
}


Gary Aitken		garya@village.org
-
This message was sent to the java-interest mailing list
Info: send 'help' to java-interest-request@java.sun.com

home help back first fref pref prev next nref lref last post