I am not able to solve this problem with returning a proper instance of a class from a generic method.
Here is my code:
interface SomeClass {}
class B extends A {}
class C extends B {}
class A<T extends SomeClass>
{
public <J extends B> J doSomething(Class<J> clazz) throws Exception
{
Constructor<J> ctr = clazz.getDeclaredConstructor();
return ctr.newInstance(new Object[]{});
}
}
class Main
{
public static void main(String[] args) throws Exception
{
A a = new A();
Object obj = a.doSomething(C.class);
System.out.println(obj.getClass());
}
}
Now a.doSomething(C.class)
returns me an instance of class A
instead of class C
.
How do I return class C
from my method and — the most importantly — why is it happening?