I
isamura
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
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