简体   繁体   English

实例化泛型类型时发出警告

[英]Warning in instantiating a generic type

I have a snippet code for instantiation of a generic type as following: 我有一个用于实例化泛型类型的代码段,如下所示:

public class GenericMessageMapper<I ,X>
{
   public X xFromI(I imf)
   {
      // do thing by imf argument
      Class<X> clazz = (Class<X>)((ParameterizedType)
                                   this.getClass()
                                       .getGenericSuperclass())
                                       .getActualTypeArguments()[1];
      X x = clazz.newInstance(); 
   }
}

Above code worked fine but MyEclipse show a warning on the code(a yellow under line on preparing clazz variable line) by this message : Type safety: Unchecked cast from Type to Class<X> 上面的代码运行良好,但是MyEclipse通过以下消息在代码上显示警告(在准备clazz变量行时,该行下方为黄色): Type safety: Unchecked cast from Type to Class<X>

I temporary add following annotation in above of xFromI method: 我在xFromI方法上方临时添加以下注释:

@SuppressWarnings("unchecked")

What is reason of this warning and what is solution? 该警告的原因是什么?解决方法是什么?

A warning is just that. 一个警告就是这样。 A warning. 一个警告。 Sometimes warnings are irrelevant, sometimes they're not. 有时警告是无关紧要的,有时则是无关紧要的。 They're used to call your attention to something that the compiler thinks could be a problem, but may not be. 它们通常被用来引起您对编译器认为可能是但可能不是问题的注意。

In the case of casts, it's always going to give a warning in this case. 在强制转换的情况下,在这种情况下总是会发出警告。 If you are absolutely certain that a particular cast will be safe, then you should consider adding an annotation like this just before the line: 如果您完全确定特定的类型转换将是安全的,则应考虑在该行之前添加这样的注释:

@SuppressWarnings (value="unchecked")

refer Type safety: Unchecked cast 请参阅类型安全性:未经检查的演员表

It only means that the type of the class is only known at runtime, so a situation could arise where you think you are supposed to get a class of type X but actually it is of other type (it doesn't know it in compile time since X can be of any type). 这仅意味着该类的类型仅​​在运行时才知道,因此可能会出现这样的情况:您认为应该获得一个X类型的类,但实际上它是其他类型的(它在编译时不知道)因为X可以是任何类型)。

Basically you can ignore this warning. 基本上,您可以忽略此警告。

ftom2 is right - in usual situation you should perform instance check ( instanceof ) before cast in case of this warning. ftom2是正确的-在这种情况下,通常应在强制转换之前执行实例检查( instanceof )。 But in your case this is impossible because generics in Java was implemented by erasure. 但是在您的情况下,这是不可能的,因为Java中的泛型是通过擦除实现的。 Class<X> is not reified type so it is impossible to use it for instance check and only way to turn off the warning is to use @SuppressWarnings(value = "unchecked") . Class<X>不是固定类型,因此无法将其用于实例检查,并且关闭警告的唯一方法是使用@SuppressWarnings(value = "unchecked") To learn more about generics you can use this book. 要了解更多关于泛型,你可以使用这个书。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM