gpt4 book ai didi

java - 如何摆脱这个泛型警告?

转载 作者:行者123 更新时间:2023-12-01 04:47:17 25 4
gpt4 key购买 nike

我正在尝试模拟一个通用接口(interface),每当我模拟它时,我都会收到以下警告:

The expression of type GenericInterface needs unchecked conversion to conform to GenericInterface<String>



我的界面是
interface GenericInterface<T>{
public T get();
}

我的测试是
@Test
public void testGenericMethod(){
GenericInterface<String> mockedInterface = EasyMock.createMock(GenericInterface.class);
}

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

如何删除此通用警告?

最佳答案

摆脱警告的正确步骤是:

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

  • 所以是这样的:
    // this cast is correct because...
    @SuppressWarnings("unchecked")
    GenericInterface<String> mockedInterface =
    (GenericInterface<String>) EasyMock.createMock(GenericInterface.class);

    指导方针

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

    • Eliminate every unchecked warning that you can.
    • If you can't eliminate a warning, and you can prove that the code that provoked the warning is typesafe, then (and only then) suppress the warning with @SuppressWarning("unchecked") annotation.
    • Always use the SuppressWarning annotation on the smallest scope possible.
    • Every time you use an @SuppressWarning("unchecked") annotation, add a comment saying why it's safe to do so.


    相关问题
  • What is SuppressWarnings (“unchecked”) in Java?
  • How do I address unchecked cast warnings?
  • Type safety: Unchecked cast


  • 重构类型转换

    在大多数情况下,也可以在泛型 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);
    }
    }

    然后在其他地方你可以简单地做:
    // compiles fine with no unchecked cast warnings!
    Set<String> names = newSet(HashSet.class);
    Set<Integer> nums = newSet(TreeSet.class);

    也可以看看
  • Java Tutorials/Generics
  • Angelika Langer's Java Generics FAQ
  • 关于java - 如何摆脱这个泛型警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3227697/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com