I'm using reflection to instanciate classes for a specific need.
Current code is like :
public final <T> T instanciate(Class<? extends T> a_clazz, Object... args) {
// Other stuff when no arg...
Class<?>[] l_argsClasses = getClassesFromObjects(args);
Constructor<?> constructor = a_clazz.getConstructor(l_argsClasses);
constructor.newInstance(args)
}
Unfortunately, i read that it will not work when given parameters are not exactly the same type in the constructor declaration.
So when i give a subclass, the constructor is not found and I get a NoSuchMethodException.
It seems that there is no mechanism to handle polymorphism here.
Example :
public class A {
}
public class B extends A {
}
public class Foo extends A {
public Foo(A a) {
}
}
Will work :
instanciate(Foo.class, new A()); // because Foo(A a)
Won't work :
instanciate(Foo.class, new B()); // because Foo(B b) does't exists
Do you have any solution to handle this issue ?
Thank you
Aucun commentaire:
Enregistrer un commentaire