[英]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.