简体   繁体   English

使用具有泛型接口的泛型实现

[英]Generics implementation using interface with generics

I have an interface Value and a class Record 我有一个接口Value和一个类Record

public interface Value<T> {
    T getRawValue();
}

public class Record<Value<T>> {

    private Value<T> value;     

    T getRecordRawValue() {
        return value.getRawValue();
    }

}

Java will not compile this and complains about the Generics declaration > . Java不会对此进行编译,并且会抱怨Generics声明>。 Could someone enlighten me as to why this is invalid syntax? 有人可以启发我为什么这是无效的语法吗?

You need bound your generic type to indicate the requirement of it being a Value<T> , and you also need to preserve the type that value Value<T> is providing, therefore your Record class requires two generic types: T: The type of the values returned and U: the type that represents a Value<T> 您需要绑定通用类型以表明它是Value<T> ,并且还需要保留Value<T>提供的值的类型,因此Record类需要两种通用类型:T:返回的值和U:表示Value<T>

public class Record<T, U extends Value<T>>

Here you have a full example of this: 这里有一个完整的例子:

public interface Value<T> {
    T getRawValue();
}

public class Record<T, U extends Value<T>> {

    public Record(U value) {
        this.value = value;
    }

    private U value;

    T getRecordRawValue() {
        return value.getRawValue();
    }

}

public class StringValue implements Value<String> {

    @Override
    public String getRawValue() {
        return "raw";
    }
}

public class StrongValue implements Value<String> {

    @Override
    public String getRawValue() {
        return "Rrrrraaawww";
    }
}

public class StringRecord extends Record<String, StringValue> {

    public StringRecord(StringValue valueProvider) {
        super(valueProvider);
    }

    public String report() {
        return super.getRecordRawValue();
    }
}

The code public class Record<Value<T>> attempts to declare a generic type parameter for the class called Value<T> , but when declaring a generic type parameter, it should be a simple identifier such as T . 代码public class Record<Value<T>>试图为名为Value<T>的类声明一个通用类型参数,但是在声明通用类型参数时,它应该是一个简单的标识符,例如T

Try 尝试

public class Record<T>

Your Record class is wrongly declared. 您的Record类被错误地声明。 It should be 它应该是

public class Record<T> {
    //contents...
}

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

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