小编ms3*_*449的帖子

如何避免Java Generics扩展Comparable接口中未经检查的强制转换?

为什么(T)这个通用接口需要不安全的转换?如果T与自身相当,也就是ExtendedComparable<super of T>那些也意味着ExtendedComparable<T>,那么为什么需要ExtendedComparable<T>将类型擦除转换为T?

/* @param <T> T must be comparable to itself or any of its superclass
 * (comparables are consumers, thus acc. to the PECS principle 
 * = producer-extends,consumer-super we use the bounded wildcard type "super")
 */   
public interface ExtendedComparable<T extends ExtendedComparable<? super T>> {
    Comparator<? super T> getComparator();
    default boolean greaterThen(T toCompare) {
        return getComparator().compare((T) this, toCompare) > 0;
    }
}
Run Code Online (Sandbox Code Playgroud)

java generics casting type-conversion type-erasure

6
推荐指数
1
解决办法
213
查看次数

标签 统计

casting ×1

generics ×1

java ×1

type-conversion ×1

type-erasure ×1