简体   繁体   中英

Type inference issue for generic method

Is it possible to resolve the problem with weak inference without defining additional variables or type casts for code below?

public class GenericClass<T> {
    public <R> R m(Class<R> cl) {
        return null;
    }
}

GenericClass<SomeClass> v2 = new GenericClass<SomeClass>()
    .m(GenericClass.class)
    .m(GenericClass.class); // <- Object cannot be converted to GenericClass<SomeClass>

Yes:

public class GenericClass<T> {
    public <R> R m(Class<? super R> cl) {
        return null;
    }
}

GenericClass<SomeClass> v2 = new GenericClass<SomeClass>()
    .<GenericClass<SomeClass>>m(GenericClass.class)
    .m(GenericClass.class);

We need to fix the fact that cl might be an erased type (ie, a super type of the generic type, R ), and then we need to tell the compiler what the real type R is since the method argument is only indicating the super type.

The second call to m doesn't not need to have the generic type specified because it is inferred from the assignment.

in order to call you method m in chain it needs to return its on class "this". In your case is GenericClass. This should work.

class GenericClass<T> {
    public <R> GenericClass<T> m(Class<R> cl) {
        // code to do something here
        return this;
    }
}

for every call to the "m" method it will return it's own class then you can call it again.

I hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM