Possible Duplicate:
How to create instance of a class with the parameters in the constructor using reflection?
Is it possible to happen and how?
I have a class Gerbil
:
public class Gerbil {
private int gerbilNumber;
public Gerbil(int gn){
this.gerbilNumber = gn;
}
public void hop() {
System.out.println("It's gerbil number" + this.gerbilNumber + "and it's hopping.");
}
}
I have a generic class TestGenerics
:
public class TestGenerics<T> {
private Class<T> mClass;
public TestGenerics(Class<T> cls){
mClass = cls;
}
public T get(){
try{
return mClass.newInstance();
}catch(Exception e){
e.printStackTrace();
return null;
}
}
}
And a main
class:
public class HelloWorld {
public static void main(String[] args) {
TestGenerics<Gerbil> g = new TestGenerics<Gerbil>(Gerbil.class);
Gerbil a = g.get();
a.hop();
}
}
The problem is that I need to provide the constructor of Gerbil
with an integer value but don't know how (if possible). Otherwise if I leave an empty/default constructor the code is working fine, but is it possible to make an instance form a generic class when the constructor of the real class need parameters to be passed?
Try this:
public T get(){
try{
return mClass.getDeclaredConstructor( Integer.TYPE ).newInstance( 10 );
}catch(Exception e){
e.printStackTrace();
return null;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With