作者:小群群zheng | 来源:互联网 | 2023-05-17 18:06
Given this code:
鉴于这种代码:
List ints = new ArrayList();
// Type mismatch:
// cannot convert from Class to Class>
Class> typeTry1 = ints.getClass();
// Type safety:
// Unchecked cast from Class to Class>
Class> typeTry2 = (Class>) ints.getClass();
// List is a raw type. References to generic type List should be parameterized
Class extends List> typeTry3 = ints.getClass();
Is there a way to get the Class
of a List
without an error or warning? I can suppress the warnings easily enough, but if Java requires me to suppress a warning for this valid code, I am very disappoint.
是否有一种方法可以在没有错误或警告的情况下获得List
的类?我可以很容易地抑制警告,但是如果Java要求我为这个有效的代码抑制一个警告,我将非常失望。
On the other hand, if warning suppression is the only way, what is the safest to suppress?
另一方面,如果警告抑制是唯一的方法,那么最安全的抑制方法是什么?
2 个解决方案
5
This is a real Catch-22 in Java.
这是Java中真正的Catch-22。
The compiler warns you if you don't add a generic type to List
:
如果不向列表中添加泛型类型,编译器会警告您:
// WARN: List is not typed
Class extends List> typeTry3 = ints.getClass();
That's because, in most cases, it's really best to type your Lists.
这是因为,在大多数情况下,最好键入列表。
However, because of type erasure, there's no way for Java to figure out the generic type of List
at runtime, and the compiler knows that. Therefore, there is no method on Class
that will returned a typed object:
但是,由于类型擦除,Java无法在运行时确定列表的泛型类型,编译器知道这一点。因此,在类上没有返回类型化对象的方法:
// ERROR: ints.getClass() doesn't return a Class>, it returns a Class
Class extends List extends Integer>> var = ints.getClass();
So you must cast it to a typed list. However, as you know, since there is no runtime type checking, Java warns you about any casts to a typed variable:
因此,您必须将其转换为类型化列表。但是,正如您所知道的,由于没有运行时类型检查,Java警告您任何类型变量的类型转换:
// WARN: Casting to typed List
Class> typeTry2 = (Class>) ints.getClass();
Any attempt to get around this is essentially a means of confusing the compiler, and will inevitably be convoluted.
任何试图绕过它的尝试本质上都是一种混淆编译器的方法,并且不可避免地会令人费解。
Your best bet then is to go with Option B:
你最好的选择是选择B:
On the other hand, if warning suppression is the only way, what is the safest to suppress?
另一方面,如果警告抑制是唯一的方法,那么最安全的抑制方法是什么?
The safest way to suppress this warning is to make your @SuppressWarnings("unchecked")
annotation as localized as possible. Put them above each individual unchecked cast. That way it's absolutely clear who's causing the warning.
抑制这个警告的最安全的方法是使您的@SuppressWarnings(“unchecked”)注释尽可能本地化。将它们放在每个未选中的cast上面。这样一来,谁会发出警告就一目了然了。