简体   繁体   English

java 中的通配符、泛型、setter 和 getter

[英]wildcard, generic, setter and getter in java

I've got a generic class with subclass.我有一个带有子类的通用 class 。

public class GenericClass<C>
{
    private C value;

    public C getValue() { return value; }

    public void setValue(C value) { this.value = value; }
}

In my code I use subclasses without knowing what subclasses but I know this two subclasses are same type:在我的代码中,我使用子类而不知道什么子类,但我知道这两个子类是相同的类型:

GenericClass<?> obj1 = ... // has a value here
GenericClass<?> obj2 = ... // has a value here

// I know that obj1 is the same type of obj2 but I don't know this type.
obj1.setValue(obj2.getValue());

The last line produce a compilation error which is:最后一行产生一个编译错误,即:

The method setValue(capture#11-of?) in the type GenericClass is not applicable for the arguments (capture#12-of?) GenericClass 类型中的方法 setValue(capture#11-of?) 不适用于 arguments (capture#12-of?)

How can I do that (something like casting a wildcard...)?我该怎么做(比如投射通配符......)?

Since GenericClass<?> holds no information of the actual enclosed type, the compiler has no way to ensure that two such classes are compatible.由于GenericClass<?>不包含实际封闭类型的信息,因此编译器无法确保两个这样的类兼容。 You should use a concrete named generic type parameter.您应该使用具体命名的泛型类型参数。 If you don't know the concrete type, you may still be able to enforce the sameness of the two type parameters by eg enclosing the above code in a generic method:如果您不知道具体类型,您仍然可以通过例如将上述代码包含在泛型方法中来强制两个类型参数的相同性:

public <T> void someMethod() {
  GenericClass<T> obj1 = ... // has a value here
  GenericClass<T> obj2 = ... // has a value here

  obj1.setValue(obj2.getValue());
}

If this is not possible, you may as a last resort try explicit casts, or using raw types.如果这是不可能的,您可以作为最后的手段尝试显式转换,或使用原始类型。 This will trade the compilation error to unchecked cast warning(s).这会将编译错误转换为未经检查的强制转换警告。

You need to type your method:您需要输入您的方法:

public static <T extends GenericClass<?>> void someMethod() {
    T obj1 = ... // has a value here
    T obj2 = ... // has a value here

    // Now they are the same type

    obj1.setValue(obj2.getValue());
}

Try that.试试看。 Let me know if it doesn't compile (and supply the code)让我知道它是否无法编译(并提供代码)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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