0

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?

Dmitriy Popov
  • 2,150
  • 3
  • 25
  • 34
  • Multiple inheritance is a different, very specific thing, which is not supported in Java. https://en.wikipedia.org/wiki/Multiple_inheritance – Michael Feb 11 '20 at 16:50
  • sorry, I meant nested inheritance, not multiple – Oleksiy Kyrylenko Feb 11 '20 at 16:51
  • 1
    Your code had multiple compilation problems. I have fixed it as best I can. If it differs from your intent, please fix it. – Michael Feb 11 '20 at 16:57
  • @Michael Hmm... you're right. I actually can't reproduce the problem... – Sweeper Feb 11 '20 at 17:01
  • 3
    Related: https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it – Sweeper Feb 11 '20 at 17:02
  • @Sweeper Me neither. The raw types are worth fixing, as always, but ultimately the call is effectively just `C.class.getConstructor()`, regardless of what the generics are doing. That can never produce an `A`. – Michael Feb 11 '20 at 17:03

0 Answers0