【问题标题】:Is it possible to return the Class of a generic type without any warning?是否可以在没有任何警告的情况下返回泛​​型类型的类?
【发布时间】:2022-01-05 01:16:56
【问题描述】:

问题很简单,看看下面的代码:

public class ChoiceBox<T> {}

public Class<ChoiceBox> getApplicableClass() {
        return ChoiceBox.class;
}

在 Eclipse 和其他 IDE 中,会生成警告:

ChoiceBox is a raw type. References to generic type ChoiceBox<T> should be parameterized

所以我确实将 getApplicableClass 函数的返回类型更改为:

public Class<ChoiceBox<?>> getApplicableClass()

但现在的问题是,我怎样才能在没有警告的情况下返回 Class>

public Class<ChoiceBox<?>> getApplicableClass() {
    return ??????????????;
}

【问题讨论】:

  • 可以在方法中添加@SuppressWarnings("rawtypes")注解。
  • 你好@MirekPluta,你是对的,但我们的目标是在可能的情况下找到一种“没有警告”的方法
  • 我认为这是不可能的。也许你的答案在stackoverflow.com/a/2390682/9901515

标签: java generics


【解决方案1】:

Effective Java by Joshua Bloch一书中明确处理了这种情况。

您不应该使用原始类型的规则有一些小例外。您必须在类文字中使用原始类型。该规范不允许使用参数化类型[在类文字中]。

您的问题的答案是:不,在这种情况下无法避免警告,除非您使用 @SuppressWarnings("unchecked") 注释。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 2010-09-08
    • 2023-03-30
    • 2012-09-19
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多