/*
* 首先判断是否实现了Comparable接口,如果实现了则判断x是不是String类型
* 如果是String类则返回该String.class
*/
static Class<?> comparableClassFor(Object x) {
if (x instanceof Comparable) {
Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
if ((c = x.getClass()) == String.class) // bypass checks
return c;
//获得类x的所有实现了的接口
if ((ts = c.getGenericInterfaces()) != null) {
for (int i = 0; i < ts.length; ++i) {
/*如果该接口用到了泛型,则获得
* 该接口,并且调用getRawType方法判断使用了泛型的接口中是否
* 有Comparable接口.
*/
if (((t = ts[i]) instanceof ParameterizedType) &&
((p = (ParameterizedType)t).getRawType() ==
Comparable.class) &&
/*获得泛型中的类,并且判断是否只用了一个泛型,并且判断该泛型的实现
类是否为 x 所属的类*/
(as = p.getActualTypeArguments()) != null &&
as.length == 1 && as[0] == c) // type arg is c
return c;
}
}
}
return null;
}
HashMap中的comparableClassFor方法
最新推荐文章于 2022-11-22 23:53:08 发布