如何摆脱这种泛型警告?

She*_*har 2 java generics easymock

我试图模拟一个通用接口,每当我模拟它,我得到这个警告:

GenericInterface类型的表达式需要未经检查的转换以符合GenericInterface <String>

我的界面是

interface GenericInterface<T>{
    public T get();
}
Run Code Online (Sandbox Code Playgroud)

我的考试是

@Test
public void testGenericMethod(){
    GenericInterface<String> mockedInterface = EasyMock.createMock(GenericInterface.class);
}
Run Code Online (Sandbox Code Playgroud)

我在测试用例的第一行收到警告.

如何删除此通用警告?

pol*_*nts 9

摆脱警告的正确步骤是:

  • 首先,证明未经检查的演员是安全的,并记录原因
  • 然后才执行未经检查的强制转换,并对@SuppressWarnings("unchecked")变量声明进行注释(不是在整个方法上)

所以像这样:

// this cast is correct because...
@SuppressWarnings("unchecked")
GenericInterface<String> mockedInterface =
    (GenericInterface<String>) EasyMock.createMock(GenericInterface.class);
Run Code Online (Sandbox Code Playgroud)

方针

以下内容摘自Effective Java 2nd Edition:第24项:消除未经检查的警告:

  • 消除所有未经检查的警告.
  • 如果您无法消除警告,并且您可以证明引发警告的代码是类型安全的,那么(并且只有这样)才能使用@SuppressWarning("unchecked")注释来抑制警告 .
  • 始终SuppressWarning在尽可能小的范围内使用注释.
  • 每次使用@SuppressWarning("unchecked")注释时,都要添加注释,说明为什么这样做是安全的.

相关问题


重构演员

在大多数情况下,也可以在一般化的内部执行未经检查的演员表createMock.它看起来像这样:

static <E> Set<E> newSet(Class<? extends Set> klazz) {
    try {
        // cast is safe because newly instantiated set is empty
        @SuppressWarnings("unchecked")
        Set<E> set = (Set<E>) klazz.newInstance();
        return set;
    } catch (InstantiationException e) {
        throw new IllegalArgumentException(e);
    } catch (IllegalAccessException e) {
        throw new IllegalArgumentException(e);          
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在其他地方你可以做到:

// compiles fine with no unchecked cast warnings!
Set<String> names = newSet(HashSet.class);
Set<Integer> nums = newSet(TreeSet.class);
Run Code Online (Sandbox Code Playgroud)

也可以看看