我目前在这一行上得到了一个编译错误:
chosenState = chosenState.withProperty(property, value);其中property是IProperty<?>,值是Comparable<?>。withProperty的签名是:
<T extends Comparable<T>, V extends T> IBlockState withProperty(IProperty<T> property, V value);IProperty的类型参数是:
IProperty<T extends Comparable<T>>编译错误是:
chosenState = chosenState.withProperty(property, value);
^
required: IProperty<T>,V
found: IProperty<CAP#1>,Comparable<CAP#2>
reason: inference variable T has incompatible bounds
equality constraints: CAP#1
lower bounds: V,Comparable<CAP#2>
where T,V are type-variables:
T extends Comparable<T> declared in method <T,V>withProperty(IProperty<T>,V)
V extends T declared in method <T,V>withProperty(IProperty<T>,V)
where CAP#1,CAP#2 are fresh type-variables:
CAP#1 extends Comparable<CAP#1> from capture of ?
CAP#2 extends Object from capture of ?我想通过查找T和V类型来解决这个问题,其中:
IProperty<?>扩展IProperty<T>Comparable<?>扩展V扩展T扩展Comparable<T>一些可以工作的类型参数是<?, ?>,但是两个?都是未知的,但类型相同,或者至少第一个?扩展了第二个。有什么方法可以告诉编译器吗?
我知道这两个?是相同的,因为value是Collection<T> getAllowedValues();方法在IProperty<T extends Comparable<T>>中返回的集合的一个元素。
我知道我可以通过转换到IProperty和Comparable来解决这个问题,但是我想避免使用原始类型。
发布于 2018-01-24 20:30:07
您必须向编译器保证V绑定到T。
使用通配符,编译器不能保证Comparable<?>将是?的子类型,因为您可以拥有不兼容的String value和IProperty<Integer>。
为了解决您的问题,您可以创建中间包装器,它将保存value和property,以保证V extends T限制,并保持对由通配符限制的Tuple<?, ?>实例的引用,而不是单独使用property和value。
public class Tuple<T extends Comparable<T>, V extends T>{
private IProperty<T> property = null;
private V value = null;
public Tuple(IProperty<T> property, V value){
this.property = property;
this.value = value;
}
public IProperty<T> getProperty() {
return property;
}
public V getValue() {
return value;
}
}
<T extends Comparable<T>, V extends T> IBlockState withProperty(Tuple<T, V> t){
return withProperty( t.getProperty(), t.getValue() );
}最后:
IProperty<String> property = ...;
String value = ...;
Tuple<?, ?> t = new Tuple<>(property, value);
withProperty(t);https://stackoverflow.com/questions/48430101
复制相似问题