[英]Generics and varargs java
以下是我的設置
public interface Test<T extends MyInterface>
{
someMethod(T... a)
}
public class TestImpl implements Test<MyInterfaceImpl>
{
someMethod(MyInterfaceImpl... a)
}
public class MyInterfaceImpl implements MyInterface {}
public someClass { @Autowired TestFactory testfactory
......
// getting an error -- Type mismatch Can't assign non-array value to an array
testfactory.getTest(Type type).someMethod(new MyInterfaceImpl())
}
public class TestFactoryImpl implements TestFactory { Test getTest(Type type) { return registry.get(type)}}
反過來又導致java.lang.ClassCastException:[Lcom.test.MyInterface; 無法轉換為[Lcom.test.Impl.MyInterfaceImpl;
但下面的工作
testfactory.getTest(Type type).someMethod(new MyInterfaceImpl[]{new MyInterfaceImpl()})
不確定發生了什么。 請幫忙
好的..問題在於您現有代碼的設計(您無法更改)。 有public interface Test<T extends MyInterface>
然后public class TestImpl implements Test<MyInterfaceImpl>
是錯誤的。
TestImpl
使用MyInterfaceImpl
實現Test
,而原始的Test
接口只需要一個extends
MyInterface
而不實現它的對象。
執行代碼時,運行時會出現類型混淆。 以下行不僅拋出ClassCastException
test.someMethod(new MyInterfaceImpl());
還有test.someMethod();
本身拋出異常。 所以,假設你工廠調用這個方法不傳遞任何參數,你仍然會得到一個例外,因為原設計是有缺陷的。 在正常情況下test.someMethod();
不應該拋出異常開始。 您需要與相關方聯系,以解決此嚴重問題。
方法someMethod(MyInterface...)
屬於原始類型Test
。 應參數化對泛型類型Test<T>
引用。
這意味着您應該Test<MyInterfaceImpl> test
以避免僅使用new
運算符獲得此錯誤。
Test<MyInterfaceImpl> test
...
test.someMethod(new MyInterfaceImpl());
上面的代碼沒有問題。
更好的解決方案是在您的TestImpl
類中執行以下操作
public class TestImpl implements Test<MyInterface>{...}
代替
public class TestImpl implements Test<MyInterfaceImpl>{...}
這樣您就不需要顯式地參數化您的對象實例(即您可以這樣做
Test test
...
test.someMethod(new MyInterfaceImpl());
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.