简体   繁体   English

Java反射:(Type)field.get(object)-未经检查的转换

[英]Java Reflection: (Type) field.get(object) - unchecked cast

Following code retrieves the value of a field using the Reflection API. 以下代码使用Reflection API检索字段的值。 As you can see in the provided image, this generates an unchecked cast warning. 如您在所提供的图像中看到的,这将生成未经检查的投射警告。 The warning can be suppressed using @SuppressWarnings("unchecked") . 可以使用@SuppressWarnings(“ unchecked”)取消警告。 I was wondering if there is an alternative to this though? 我想知道是否有替代方法?

Update: KeyType is a generic. 更新:KeyType是通用的。 So KeyType.class.cast(object); 所以KeyType.class.cast(object); wouldn't work due to type erasure. 由于类型擦除而无法使用。

private K getId(Field idField, V o) {
    K id = null;
    try {
        idField.setAccessible(true);
        id = (K) idField.get(o);
    } catch (IllegalAccessException ignored) {
        /* This never occurs since we have set the field accessible */
    }
    return id;
}

未经检查的投放警告


Solution: Seems like the SuppressWarnings annotation IS the way to go here.. thanks for your time guys. 解决方案:好像是SuppressWarnings注释是到达这里的方式。.谢谢您的时间。

解

The Class method cast doesn't require the @SupressWarnigns even though it still can throw ClassCastException. 尽管Class方法强制转换仍然可以引发ClassCastException,但它不需要@SupressWarnigns。

KeyType keyType = KeyType.class.cast( idField.get(o) );

You can - since at that location you should know the generic paramter(s) - proceed like this: 您可以-因为在该位置您应该知道通用参数-像这样进行:

private static class ListInteger extends ArrayList<Integer>{}

Object obj = new ArrayList<Integer>();
ListInteger test = ListInteger.class.cast(obj);

Once you have an object of class KeyType you can, of course, 当然,一旦有了KeyType类的对象,就可以

KeyType keyTypeX = ...; // not null

KeyType keyType = keyTypeX.getClass().cast( obj );

There are alternatives, although the @SuppressWarnings isn't so bad - try to limit it to an declaration+assignment, don't put it on the method. 还有其他选择,尽管@SuppressWarnings并不是很糟糕-尝试将其限制为声明+赋值,但不要将其放在方法中。

The signature of get method of Field is Field的get方法的签名是

public Object get(Object obj) { 
 ...
}

Since it is not generic, the return type is Object, you cannot enforce any error to appear at compile-time . 由于它不是通用的,因此返回类型为Object,因此您不能强制在编译时出现任何错误。

If you are sure that the type of the value is ValueType all the time, then add documentation to the method, saying the type will be always ValueType and use @SuppressWarnings("unchecked"). 如果您是确保该值的类型是ValueType的时候,再加入文档的方法,并称类型将永远值类型和使用@SuppressWarnings(“未登记”)。

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

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