I was wondering if I am using Reflection in a way that was not intended...or not possible.
I want to store a class, MyClass0 in a variable:
Class cls = Class.forName("MyClass0");
Later I want to instantiate a new instance from 'cls':
MyClass0 inst;
Constructor cons = cls.getConstructor(new Class[]);
inst = cons.newInstance(new Object[]);
...
This is fine so far. But what if I have several classes: MyClass1, MyClass2.
I also want to reuse the above code to create new instances of these classes.
The problem is in the variable declaration statement:
MyClass0 inst;
The type could be any of the three classes. Obviously
cls inst;
won't compile.
Alternatively,
Object inst;
Constructor cons = cls.getConstructor(new Class[]);
inst = cons.newInstance(new Object[]);
produces type mismatch compiler error.
I tried to cast the instance creation:
inst = (cls)cons.newInstance(new Object[]);
but that didn't work either. Perhaps I am missing something.
So what else is possible, besides forgetting code reuse in this situation? <g>
Thanks!
.K
Alexey_Volynskyy - 18 Oct 2005 08:27 GMT
> I was wondering if I am using Reflection in a way that was not intended...or not possible.
>
[quoted text clipped - 31 lines]
>
> Thanks!
Do this way:
> Class cls = Class.forName("MyClass0"); //This is correct.
Object inst ;
inst = cls.newInstance(); //calls constructor without parameters
If you want to call specific contructor, you can get all contructors
available:
Constructor[] constrs = cls.getContructors();
Then select needed constructor and call it:
Object inst1 = constrs[0].newInstance(Object[] initArgs);
BR
Alexey
Roedy Green - 18 Oct 2005 09:07 GMT
>So what else is possible, besides forgetting code reuse in this situation? <g>
All your classes could implement the same interface.
All could derive from the same base.
You do call all the methods via reflection and just call the instances
Objects.

Signature
Canadian Mind Products, Roedy Green.
http://mindprod.com Again taking new Java programming contracts.
isamura - 18 Oct 2005 18:52 GMT
: >So what else is possible, besides forgetting code reuse in this situation? <g>
:
: All your classes could implement the same interface.
: All could derive from the same base.
: You do call all the methods via reflection and just call the instances
: Objects.
Jollygood! My classes do use the same base (same inheritance hierarchy) but the key was a common
interface.
I did thought about using more reflection but decided against it for code maintenance reasons.
The code compiles now. Let's see if it runs <g>
Thanks again for your helpful input.
Cheers!
.K