What is the cause of this compilation error using java generics and reflection?

I have a generic method that should be similar to recursion, but call different instances of the method for each call

public <M extends A> void doSomething(Class<M> mClass,M mObject)
{
    // ... Do something with mObject.

    A object = getObject();
    Class<? extends A> objectClass = object.getClass();

    doSomething(objectClass,objectClass.cast(object)); // Does not compile.
}

private A getObject() {...}

The problem is that the comment line cannot be compiled, giving the following error:

I don't quite understand why the compiler can't compile if it can call dosomething with M = "? Extensions a"

Why not compile?

Solution

The language doesn't track wildcards like that (it seems) What you need to do is capture the wildcard, which can be done through type inference method calls

public <M extends A> void doSomething(Class<M> mClass,M mObject) {
    // ... Do something with mObject.

    A object = getObject();
    Class<? extends A> objectClass = object.getClass();
    privateSomething(objectClass,object);
}
private <T extends A> void privateSomething(Class<T> objectClass,A object) {
    doSomething(objectClass,objectClass.cast(object)); // Should compile.
}

As usual, although reflection has some uses, it is usually a sign of confusion

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>