开发者

generic type parameter

开发者 https://www.devze.com 2023-02-22 13:12 出处:网络
I\'ve defined the following classes public class AbstractManager<E> { public E save(E o) { // Implementation omitted

I've defined the following classes

public class AbstractManager<E> {

    public E save(E o) {
        // Implementation omitted
    }

    public <T> T getSingleResult(Query query, Class<T> clazz) {
        return clazz.cast(query.getSingleResult());
    }
}

public class MatchingAlgorithmManagerImpl extends AbstractManager {

    void someMethod() {
        // compiler error: "Type mismatch: cannot convert from Object to Country"
        Country c = this.getSingleResult(query, Country.class);
    }
}

I'm very confused about why I'm getting this compiler error, surely it should be using Country as the value for <T> whereas it seems 开发者_如何学Pythonto be using Object, which I presume is the default for the <E> when I don't specify a parametric type.

Even stranger, if I change the subclass definition to public class MatchingAlgorithmManagerImpl extends AbstractManager<Object>, the error disappears.

Why does the type I define for E have any relevance?


When you use a raw type, the compiler indeed removes all generic types, both those related to the class parameter types (E in your case), and those that are not (T in your case).

So when you don't parametrise your extension, even your T gets erasured (is that a verb?) to Object, which explains the error.

Good references can be found from Non-generic reference to generic class results in non-generic return types


Your class declaration for AbstractManager contains a generic parameter, but when you are extending that class you are using a raw type, try

public class MatchingAlgorithmManagerImpl extends AbstractManager<Country>
0

精彩评论

暂无评论...
验证码 换一张
取 消