簡體   English   中英

如何告訴Java兩個“?”是同一類型?

[英]How can I tell Java that two “?”s are the same type?

我目前在這一行收到編譯錯誤:

chosenState = chosenState.withProperty(property, value);

其中propertyIProperty<?> ,value是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 ?

我想通過查找類型TV來解決它,其中:

  • IProperty<?>擴展了IProperty<T>
  • Comparable<?>擴展V extends T擴展Comparable<T>

一些可行的類型參數是<?, ?> ,但兩者都有? s是未知但類型相同,或至少第一個? 延伸第二個。 有沒有辦法告訴編譯器?

我知道這兩個? s是相同的,因為valueCollection<T> getAllowedValues();返回的集合的元素Collection<T> getAllowedValues(); IProperty<T extends Comparable<T>>方法IProperty<T extends Comparable<T>>

我知道我可以通過轉換為IPropertyComparable來解決這個問題,但我想避免使用原始類型。

您必須向編譯器保證V綁定到T

使用通配符,編譯器無法保證Comparable<?>將成為子類型? 因為你可以擁有不兼容的String valueIProperty<Integer>

要解決您的問題,您可以創建保存valueproperty中間包裝器,以保證V extends T限制並保持對通配符限制的Tuple<?, ?>實例的引用,而不是單獨使用propertyvalue

    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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM