简体   繁体   中英

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>) .

As can be seen in the code, the wildcard ( ? extends ConnectionBase ) and generic type ( T extends ConnectionBase ) are the same.

How can I get rid of the Unchecked cast warning and convert without warnings from the wildcard to the generic type?

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

B extends A

C extends A

B and C are not safe to cast between.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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