简体   繁体   English

如何在不使用 Java 中的泛型的情况下解决对 compareTo(T) 的未经检查的调用

[英]How to resolve unchecked call to compareTo(T) without using generics in Java

I would like to resolve this compiler warning:我想解决这个编译器警告:

unchecked call to compareTo(T) as member of the raw type java.lang.Comparable

My goal is to compare two java.lang.Object objects of unknown (background) type using following method.我的目标是使用以下方法比较未知(背景)类型的两个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...
}

I know that the problem is that the method casts both objects to Comparable ( Comparable<Object> ), but Object does not implements Comparable .我知道问题在于该方法将两个对象都转换为Comparable ( Comparable<Object> ),但Object没有实现Comparable

The code itself works , but the compiler throws a warning when using its -Xlint:unchecked parameter.代码本身有效,但编译器在使用其 -Xlint:unchecked 参数时会抛出警告。

Goals:目标:

  • remove the compiler warning删除编译器警告
  • keep out of other 'unchecked' warnings远离其他“未经检查”的警告
  • avoiding using @SupressWarning避免使用@SupressWarning
  • keep Compare method non-generic保持比较方法非通用

You can't easily escape the compiler warnings.您无法轻松逃脱编译器警告。 It is its job to tell you when you're doing type manipulations that can break at runtime.它的工作是在您进行可能在运行时中断的类型操作时告诉您。 The only way to fulfill your goal is to do even more unchecked manipulations, like this :实现目标的唯一方法是进行更多未经检查的操作,如下所示:

    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;

    }

The best option is still to use @SuppressWarnings once when converting the objects, and get on with it.最好的选择仍然是在转换对象时使用@SuppressWarnings一次,然后继续使用它。 If somehow you can't guarantee the type safety of your parameters, it's perfectly OK to use it.如果你不能保证参数的类型安全,那么使用它是完全可以的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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