Simple Class.forname question

Hi all,

I would like to dynamically load a class. I have read the javadocs for Class and found forname the best choice.



So im doing this:



SomeObject = (SomeObject)Class.forname("com.somePackage.SomeObject").newInstance();



1) Is that the right way to do it?
2) in the Javadocs, it says:

Creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list. The class is initialized if it has not already been initialized.


Ive emphasised some words because I would like to give arguments, more specifically, a String and a Spatial.

How would I go about doing this?

Thx a zillion million gagillion, DP

SomeObject SomeVarName= (SomeObject)Class.forname("com.somePackage.SomeObject").newInstance();



I do not know of a way to use arguments. You can try having a init mehted to call after being created.

SomeObject SomeVarName= (SomeObject)Class.forname("com.somePackage.SomeObject").newInstance();

SomeVarName.init(<arguments>)
 

ive found a way using this method:



http://www.ictp.trieste.it/~manuals/programming/Java/tutorial/reflect/object/arg.html



is this the right way to do it?



DP

This will be helpful. I can’t beleve that I did not know about it. :smiley:

I didn’t look too deap but yea that’s how it’s done. I did some google’ing on it some time ago and found a pretty descriptive doc at sun’s site that helped me.

For everybody’s reference… (I just had to do this a few weeks ago…)



// Assuming you want to create 'MyClass'


  // 'path' is the path to where 'MyClass' is located
String className = path + "MyClass";
Class someClass = Class.forName(className);

  // You need to tell the constructor what types of objects
  //   it's going to get as parameters.  Do that here.  I think
  //   this format works, but didn't try it.
Class[] paramClasses = new Class[] {String.class, int.class};
Constructor ctor = someClass.getConstructor(paramClasses);

  // Now create the object with some parameters to the constructor
Object[] params = new Object[] {"Some String", new Integer(3)};
Object newItem = ctor.newInstance(params);

  // Now type-cast to get the correct object type.
MyClass abc = (MyClass)newItem;

// You will also need to catch some exceptions, here.


// All of the above is equivalent to:
// MyClass abc = new MyClass("Some String", 3);




That being said.. I feel like I should add that using reflection is generally discouraged. You lose compile-time checking, it's slow, and generally tends to be much more difficult to debug. Sometimes its the best way to go, though.. so it's just a warning.

Hope this helps.


[Edit: This is more or less what the link says. Heh. Oh well.]


--K