>>> Was wondering when using something like this
>>> theClass= (myClass)Class.forName(className).newInstance();
[quoted text clipped - 16 lines]
>
> Thanks would you happen to have an example?
Assume you have a class like this:
class A {
A (int i, float f) { ... }
}
then you can write code like this:
Constructor c = A.class.getConstructor(new Class[]{Integer.TYPE,
Float.TYPE});
A a = (A)c.newInstance(new Object[]{new Integer(1), new Float(1.0f)});
A_Wieminer - 26 Jul 2005 11:20 GMT
>>>>Was wondering when using something like this
>>>>theClass= (myClass)Class.forName(className).newInstance();
>>>>
>>>>it calls the classes (className in this case) default constructor with
>>>>no arguments right? How do you send values/arguments to it? Or can't
>>>>that be done?
>>>The Class newInstance method is a simple way of doing simple cases.
>>>Use the getConstructor method in the Class object to obtain the
>>>Constructor for your parameter types. Constructor has a newInstance
>>>method that takes a parameter array.
> Assume you have a class like this:
> class A {
[quoted text clipped - 4 lines]
> Float.TYPE});
> A a = (A)c.newInstance(new Object[]{new Integer(1), new Float(1.0f)});
For this reason if can lock your code to a homemade/stable interface you
can survive with the simple way. I often make the following design,
where I add init(...) method to make actual initialization. I then
simple use classForName and call init method with appropriate params.
theClass=(MyClass)Class.forName(className).newInstance();
theClass.init(123, 12.123);