Reputation:
I have an interface Value and a class 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 > . Could someone enlighten me as to why this is invalid syntax?
Upvotes: 1
Views: 124
Reputation: 37435
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>
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();
}
}
Upvotes: 7
Reputation: 85779
Your Record
class is wrongly declared. It should be
public class Record<T> {
//contents...
}
Upvotes: 1
Reputation: 178263
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
.
Try
public class Record<T>
Upvotes: 2