简体   繁体   English

为什么Eclipse为什么抱怨不安全的类型转换?

[英]Why does Eclipse complain about unsafe type casting?

Consider the following code: 考虑以下代码:

public static <T extends SomeObject> List<T> getByClassName(String className) throws GetRecordsException {
    try {
        Class<T> clazz = (Class<T>) Class.forName(className).asSubclass(SomeObject.class);
        return getByClassName(clazz);
    } catch (ClassNotFoundException e) {
        throw new GetRecordsException("Failed to get class forName: " + className, e);
    }
}

Eclipse is highlighting the cast (Class<T>) with the following message: Eclipse通过以下消息突​​出显示了强制转换(Class<T>)

Type safety: Unchecked cast from Class<capture#2-of ? extends SomeObject> to Class<T>

Why is this, considering that T is supposed to be guaranteed to extend from SomeObject in the method signature? 为什么这样做,考虑到应该保证方法签名中的TSomeObject扩展呢? What scenario might exist where this would be unsafe? 在不安全的情况下可能会出现什么情况?

The caller of getByClassName specifies T to be any subclass of SomeObject , but that doesn't have to be the same subclass as the one named by className . 调用者 getByClassName指定T是的任何子类SomeObject ,但这并不必须是同一小类由指定的一个className Think of <T extends SomeObject> as indicating that the type variable T is another argument passed into the method call. <T extends SomeObject>视为表明类型变量T是传递给方法调用的另一个参数。

So for example, an unsafe usage would be foo.<SomeObjectSubclass1>getByClassName("SomeObjectSubclass2") -- that syntax is how you specify type arguments explicitly, instead of letting them be inferred -- and then that'd return a List<SomeObjectSubclass1> that actually contained SomeObjectSubclass2 , and everything would be a disaster. 因此,例如,不安全的用法将是foo.<SomeObjectSubclass1>getByClassName("SomeObjectSubclass2") -该语法是您显式指定类型参数的方式,而不是让它们被推断-然后返回List<SomeObjectSubclass1>实际上包含SomeObjectSubclass2 ,一切都将是一场灾难。

What you could do safely is let clazz be a Class<? extends SomeObject> 您可以安全地做的就是让clazz成为Class<? extends SomeObject> Class<? extends SomeObject> , and then return a List<? extends SomeObject Class<? extends SomeObject> ,然后返回List<? extends SomeObject List<? extends SomeObject . List<? extends SomeObject

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

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