简体   繁体   English

如何做一组通用值?

[英]How do I do a set of a generic value?

I have the following defined:我定义了以下内容:

public class myClass<T> {
    private T value;

    protected <T> void setValue(T value) {
        if (value != null) // optional
            this.value = value;
    }
}

However I get a compilation error with this:但是我得到一个编译错误:

Type mismatch: cannot convert from T to T

(I know, helpful and logical right?). (我知道,有用且合乎逻辑吗?)。

What's the proper way to setup this method?设置此方法的正确方法是什么? Also note, the signature is setup in an abstract class like this:另请注意,签名是在抽象 class 中设置的,如下所示:

@SuppressWarnings("hiding")
protected abstract <T> void setValue(T value);

You have two unrelated T types.你有两种不相关的T类型。 In your method declaration, <T> re-declares a type T , hiding the class-level type variable.在您的方法声明中, <T>重新声明了一个类型T ,隐藏了类级别的类型变量。

In short, you don't need the method to be generic, because you want setValue to take the type declared on the class.简而言之,您不需要该方法是通用的,因为您希望setValue采用 class 上声明的类型。 Because the type parameter is available throughout the class, your method should be as simple as:因为 type 参数在整个 class 中都可用,所以您的方法应该很简单:

protected void setValue(T value) {
    if (value != null)
        this.value = value;
}

If your abstract class is generic too, then the same correction needs to be made in it too.如果您的抽象 class 也是通用的,那么也需要对其进行相同的更正。 Otherwise, you need to revisit its design as having a method taking randomly typed values isn't exactly right.否则,您需要重新审视其设计,因为采用随机输入值的方法并不完全正确。

You already have defined T at class level, if you put it again in the method it takes it as another T. Look at the error message I get when trying to compile your code.您已经在 class 级别定义了 T,如果您再次将其放入方法中,它将作为另一个 T。查看我在尝试编译代码时收到的错误消息。

MyClass.java:6: error: incompatible types: T#1 cannot be converted to T#2
        this.value = value;
                     ^
  where T#1,T#2 are type-variables:
    T#1 extends Object declared in method <T#1>setValue(T#1)
    T#2 extends Object declared in class MyClass
1 error

Just remove the second declaration of T and it will compile as intended.只需删除 T 的第二个声明,它就会按预期编译。

public class MyClass<T> {
    private T value;

    protected void setValue(T value) {
        if (value != null) {
            this.value = value;   
        }
    }
}

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

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