![](/img/trans.png)
[英]Implementing Comparable, compareTo name clash: “have the same erasure, yet neither overrides the other”
[英]Name clash - have the same erasure yet neither overrides the other in method parameter generic
我已經閱讀了有關Name clash - have the same erasure yet neither overrides the other
所有問題和答案Name clash - have the same erasure yet neither overrides the other
但仍然無法理解如何解決問題。 所以,
@Dependent
public class SimpleFoo {}
@Dependent
public class AdvancedFoo extends SimpleFoo {}
@Dependent
public class Parent {
@Inject
protected void setFooInstance(Instance<? extends SimpleFoo> instance) {}
}
@Dependent
public class Child extends Parent {
@Override
protected void setFooInstance(Instance<AdvancedFoo> instance) {} //Error here
}
怎么解決?
問題是Child
類聲明覆蓋以下方法:
@Override
protected void setFooInstance(Instance<AdvancedFoo> instance) {} //Error here
但Parent
類聲明了一個具有不同簽名的setFooInstance
方法:
protected void setFooInstance(Instance<? extends SimpleFoo> instance) {}
1)以這種方式覆蓋Child
類:
public class Child extends Parent {
@Override
protected void setFooInstance(Instance<? extends SimpleFoo> instance){... }
}
或者2)其他方式:如果你想強制子類中的覆蓋方法聲明一個特定的SimpleFoo
,那么使Parent
類成為一個用SimpleFoo
或它的子類參數化的泛型類:
@Dependent
public class Parent <T extends SimpleFoo>{
@Inject
protected void setFooInstance(Instance<T> instance) {...}
}
現在可以聲明Child
類:
@Dependent
public class Child extends Parent<AdvancedFoo> {
@Override
protected void setFooInstance(Instance<AdvancedFoo> instance) {...}
}
如果將Child
變為泛型類,則可以執行所需操作。 然后讓Parent
擴展特定類型的Child
,如圖所示。
public class Child<T extends SimpleFoo> {
protected void setFooInstance(Instance<T> instance) {}
}
public class Parent extends Child<AdvancedFoo> {
@Override
protected void setFooInstance(Instance<AdvancedFoo> instance) {}
}
順便說一句,你的命名有點令人困惑。 大多數人都希望Child
延伸Parent
- 而不是相反。
您希望Parent.setFooInstance
可以與Instance< SimpleFoo>
所有可能后代一起調用。 由於您只允許將Instance<Advanced>
作為參數,因此不適用於Child
類型的對象。 因此它不會以這種方式覆蓋。 否則代碼只知道調用setFooInstance
的Parent
類可能會調用錯誤類型的對象。 因此,您要么將Parent
方法的參數限制為AdvancedFoo
要么允許Child.setFooInstance
也處理SimpleFoo
后代。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.