简体   繁体   中英

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:

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

You have two unrelated T types. In your method declaration, <T> re-declares a type T , hiding the class-level type variable.

In short, you don't need the method to be generic, because you want setValue to take the type declared on the class. Because the type parameter is available throughout the class, your method should be as simple as:

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. 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.

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.

public class MyClass<T> {
    private T value;

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

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