我想解决这个编译器警告:
unchecked call to compareTo(T) as member of the raw type java.lang.Comparable
我的目标是使用以下方法比较两个未知(背景)类型的java.lang.Object
对象。
public static boolean Compare(Object o1, Object o2) {
//check if both classes are the same
if(!o1.getClass().equals(o2.getClass())) {
return false;
}
if(Comparable.class.isAssignableFrom(o1.getClass())
&& Comparable.class.isAssignableFrom(o2.getClass())) {
//only if both objects implement comparable
return Comparable.class.cast(o1).compareTo(Comparable.class.cast(o2)) == 0;
}
//other comparison techniques...
}
我知道问题是该方法将两个对象都转换为Comparable
(Comparable<Object>
),但Object
没有实现Comparable
。
代码本身可以工作,但编译器在使用-Xlint:unchecked参数时会抛出警告。
目标:
您无法轻松逃避编译器警告。当你进行可以在运行时中断的类型操作时,它的工作就是告诉你。实现目标的唯一方法是进行更多未经检查的操作,如下所示:
if(Comparable.class.isAssignableFrom(o1.getClass())
&& Comparable.class.isAssignableFrom(o2.getClass())) {
// Cache this somewhere if you're really going to use it
Method compareTo = Comparable.class.getMethod("compareTo", Object.class);
Integer result = (Integer) compareTo.invoke(o1, o2);
return result == 0;
}
转换对象时,最好的选择仍然是使用@SuppressWarnings
,并继续使用它。如果你不能保证参数的类型安全,那么使用它是完全可以的。