本文介绍了Java泛型:不兼容的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用类MyClass<T>,带有一个静态工厂方法和一个setter方法:

I have a generic class MyClass<T> with a static factory method and a setter method:

public class MyClass<T> {
    public static <T> MyClass<T> with(Context context) {
        MyClass<T> myClass = new MyClass<>();
        myClass.context = context;
        return myClass;
    }
    public void setClass(Class<? extends CustomClass<T>> customClass) {
        ...
    }
    ...
}

使用setter方法,用户可以设置任何从"CustomClass"扩展的类.

With the setter method, user can set any class that extends from "CustomClass".

到目前为止,一切都很好.如果我这样做:

So far so good. If I do:

MyClass<String> myClass = MyClass.with(this);
myClass.setClass(MyCustomClass.class);

它完美地工作.但是,如果我这样做:

It works perfectly. But if I do:

MyClass.with(this).setClass(MyCustomClass.class);

它不能编译!编译器输出:

It does not compile! The compiler outputs:

Error:(44, 87) error: incompatible types: Class<MyCustomClass> cannot be converted to Class<? extends MyCustomClass<Object>>

我不知道为什么它不能用第二个选项编译. MyCustomClass就像:

I don't know why it wont compile with the second option. MyCustomClass is like:

public class MyCustomClass extends CustomClass<String>

推荐答案

请注意,在工作示例与单行代码之间存在编译错误,因此缺少信息.

Please note that you got information missing between your working example and your one-liner which has compilation error.

它不知道专业化.您需要做类似的事情

It doesn't know the specialization. You need to do something like

MyClass.<String>with(this).setClass(MyCustomClass.class);

,所以它知道您将与它交谈".

so it knows you will be 'talking strings' to it.

这篇关于Java泛型:不兼容的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 14:05