簡體   English   中英

名稱沖突 - 具有相同的擦除但在方法參數generic中不會覆蓋另一個

[英]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類型的對象。 因此它不會以這種方式覆蓋。 否則代碼只知道調用setFooInstanceParent類可能會調用錯誤類型的對象。 因此,您要么將Parent方法的參數限制為AdvancedFoo要么允許Child.setFooInstance也處理SimpleFoo后代。

暫無
暫無

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

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