use*_*275 3 java generics interface variadic-functions
以下是我的设置
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)}}
Run Code Online (Sandbox Code Playgroud)
反过来又导致java.lang.ClassCastException:[Lcom.test.MyInterface; 无法转换为[Lcom.test.Impl.MyInterfaceImpl;
但下面的工作
testfactory.getTest(Type type).someMethod(new MyInterfaceImpl[]{new MyInterfaceImpl()})
Run Code Online (Sandbox Code Playgroud)
不确定发生了什么.请帮忙
好的..问题在于您现有代码的设计(您无法更改).有public interface Test<T extends MyInterface>,然后public class TestImpl implements Test<MyInterfaceImpl>是错的.
TestImpl正在实现Test,MyInterfaceImpl而原始Test接口只期望一个对象extends MyInterface而不实现它.
执行代码时,运行时会出现类型混淆.以下行不仅会抛出一个ClassCastException
test.someMethod(new MyInterfaceImpl());
Run Code Online (Sandbox Code Playgroud)
但test.someMethod();它本身也会引发异常.所以,假设你工厂调用这个方法不传递任何参数,你仍然会得到一个例外,因为原设计是有缺陷的.在正常情况下test.someMethod();不应该抛出异常开始.您需要与相关方联系,以解决此严重问题.
该方法someMethod(MyInterface...)属于原始类型Test.Test<T>应参数化对泛型类型的引用.
这意味着您应该Test<MyInterfaceImpl> test避免仅与new操作员一起出现此错误.
Test<MyInterfaceImpl> test
...
test.someMethod(new MyInterfaceImpl());
Run Code Online (Sandbox Code Playgroud)
上面的代码没有问题.
| 归档时间: |
|
| 查看次数: |
631 次 |
| 最近记录: |