简体   繁体   English

泛型方法参数的getClass()强制转换安全

[英]getClass() of a generic method parameter cast safety

Is this cast safe? 这个演员安全吗?

private <T> void foo(T value) {
    final Class<T> aClass = (Class<T>) value.getClass();
} 

Does a more elegant way exist to do this? 是否存在更优雅的方式来执行此操作?

Is it possible to avoid unchecked cast warning? 是否可以避免未经检查的投放警告?

You can suppress the compiler warning. 您可以禁止编译器警告。 See What is SuppressWarnings ("unchecked") in Java? 请参阅什么是Java中的SuppressWarnings(“未选中”)?

Compiler is warning you for a reason. 编译器出于某种原因警告您。 value can contain an object of some subtype of T and there are important differences between Class<Parent> and Class<Child> . value可以包含T的某些子类型的对象,并且Class<Parent>Class<Child>之间存在重要区别。 In your case, you can see that you are not doing anything unsafe, but the compiler just follows the rules. 就您而言,您可以看到您所做的任何事情都不是不安全的,但是编译器只是遵循规则。

Imagine if the method was slightly different and there was a way to get another value of type T : 想象一下,如果方法略有不同,并且有一种方法可以获取另一个T类型的值:

<T> void foo(T a, T b) {
    final Class<T> aClass = (Class<T>) a.getClass();

    // What can go wrong?  casting T to T
    T c = aClass.cast(b);
}

// but what if the two parameters are of different classes at runtime
foo(5, 5.5);   // ClassCastException!

Or what if we allow Class<T> to escape as a return value: 或者,如果我们允许Class<T>转义为返回值,该怎么办:

<T> Class<T> foo(T val) {
    final Class<T> aClass = (Class<T>) val.getClass();
    return aClass;
}

// uhoh is declared as Class<Number> but contains Class<Integer> at runtime
Class<Number> uhoh = foo(5);

// Ok to cast Double to Number but not to Integer
Number num = uhoh.cast(5.5);  // ClassCastException!

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

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