简体   繁体   English

如何在没有未经检查的强制转换警告的情况下从通配符转换为通用返回类型

[英]How to go from wildcard to generic return type without unchecked cast warning

The following code is producing an Unchecked cast warning because of the cast of (GenericKeyedObjectPool<String, T>) . 由于(GenericKeyedObjectPool<String, T>) ,以下代码将产生Unchecked cast警告。

As can be seen in the code, the wildcard ( ? extends ConnectionBase ) and generic type ( T extends ConnectionBase ) are the same. 从代码中可以看出,通配符( ? extends ConnectionBase )和通用类型( T extends ConnectionBase )是相同的。

How can I get rid of the Unchecked cast warning and convert without warnings from the wildcard to the generic type? 如何摆脱Unchecked cast转换警告,并在没有警告的情况下将通配符转换为通用类型?

private Map<String, GenericKeyedObjectPool<String, ? extends ConnectionBase>> poolMap 
     = new HashMap<>();

public <T extends ConnectionBase> T borrowObject(
        String guid, 
        Class<T> connClass) 
        throws Exception {
    GenericKeyedObjectPool<String, T> pool 
        = (GenericKeyedObjectPool<String, T>) poolMap.get(connClass.getName());
    return pool.borrowObject(guid);
}

The cast is unsafe. 演员阵容不安全。

if A isConnectionBase 如果A isConnectionBase

B extends A B延伸A

C extends A C延伸A

B and C are not safe to cast between. B和C之间的转换不安全。

To make the cast safe, you need to make it redundant by specifying the type of T at the class level to enforce it is same class throughout the class. 为了使转换安全,您需要通过在类级别上指定T的类型来使其强制冗余,以在整个类中强制它是同一类。

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

相关问题 java 转换泛型类型,没有未经检查的转换警告 - java cast generic type without unchecked cast warning 仅在通用类型上取消选中投射警告 - Unchecked cast warning only on generic type 通配符泛型和泛型之间未经检查的强制转换 - Unchecked cast between wildcard generic type and generic type 如何解决类型安全警告从集合到列表的未经检查的强制转换 <File> 没有抑制注释的Java 6 - How to address Type safety warning Unchecked cast from Collection to List<File> Java 6 without suppress annotation 转换为泛型类型(T)会发出“未经检查的强制转换”警告 - Cast to generic type (T) gives “unchecked cast” warning 从泛型类型到相同类型的未经检查的强制转换 - Unchecked cast from generic type to the same type 为什么我会收到此泛型类型的未经检查的转换警告? - Why do I get an unchecked cast warning on this generic type? 如何封装未经检查的强制类型转换以仅允许未经检查的泛型类型转换? - How to encapsulate an unchecked cast to only allow unchecked generic type conversion? 未选中投射警告:将对象强制转换为通用 - Unchecked Cast warning: cast Object to Generic 在return语句中对未选中的强制转换进行警告 - warning on unchecked cast on a return statement
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM