如何摆脱这个泛型警告?
我试图模拟一个通用接口,每当我模拟它时,我都会收到此警告:
GenericInterface 类型的表达式需要未经检查的转换以符合 GenericInterface
我的界面是
interface GenericInterface<T>{
public T get();
}
,我的测试是
@Test
public void testGenericMethod(){
GenericInterface<String> mockedInterface = EasyMock.createMock(GenericInterface.class);
}
我在测试用例的第一行收到警告。
如何删除此一般警告?
I am trying to mock a generic interface, and whenever I mock it, I gets this warning:
The expression of type GenericInterface needs unchecked conversion to conform to GenericInterface<String>
My interface is
interface GenericInterface<T>{
public T get();
}
and my test is
@Test
public void testGenericMethod(){
GenericInterface<String> mockedInterface = EasyMock.createMock(GenericInterface.class);
}
I get warning at the first line in test case.
How do I remove this generic warning?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
消除警告的正确步骤是:
所以像这样:
指南
以下摘录自有效的 Java 第二版:第 24 项:消除未经检查的警告< /em>:
相关问题
SuppressWarnings (“unchecked”)
是什么?重构强制转换
在大多数情况下也可以在通用
createMock
中执行未经检查的强制转换。它看起来像这样:然后在其他地方你可以简单地做:
另请参阅
The correct steps to get rid of the warning is:
@SuppressWarnings("unchecked")
on the variable declaration (not on the whole method)So something like this:
Guidelines
The following is excerpt from Effective Java 2nd Edition: Item 24: Eliminate unchecked warnings:
Related questions
SuppressWarnings (“unchecked”)
in Java?Refactoring the cast
It is also possible in most cases to perform the unchecked cast inside a generified
createMock
. It looks something like this:Then elsewhere you can simply do:
See also
这里的问题是 EasyMock.createMock() 将返回(不过我认为这只是给出了不同的警告。)
GenericInterface
类型的对象,而不是GenericInterface
类型。您可以使用 @SupressWarnings 注释来忽略警告,或者您可以尝试显式转换为 GenericInterfaceThe problem here is that EasyMock.createMock() is going to return an object of type
GenericInterface
and notGenericInterface<String>
. You could use the@SupressWarnings
annotation to ignore the warning, or you could try and explicit cast toGenericInterface<String>
(I think this just gives a different warning though.)似乎讨论了相同的警告......
我想@SuppressWarnings可能是这种情况下幸福的关键
seem to discuss the same warning...
i guess @SuppressWarnings might be the key to happiness in that case
如果您真的坚持避免编译器警告,您可以在测试中声明一个接口,只是为了避免它。
然后你可以这样做:
If you are really stuck up on avoiding the compiler warning, you can declare an interface in your test just for the purpose of avoiding it.
Then you can do: