简体   繁体   中英

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.

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 .

The code itself works , but the compiler throws a warning when using its -Xlint:unchecked parameter.

Goals:

  • remove the compiler warning
  • keep out of other 'unchecked' warnings
  • avoiding using @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. If somehow you can't guarantee the type safety of your parameters, it's perfectly OK to use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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