Comparing the values of two generic Numbers

后端 未结 12 1805
小鲜肉
小鲜肉 2020-11-27 04:48

I want to compare to variables, both of type T extends Number. Now I want to know which of the two variables is greater than the other or equal. Unfortunately I

12条回答
  •  不知归路
    2020-11-27 05:34

    If your Number instances are never Atomic (ie AtomicInteger) then you can do something like:

    private Integer compare(Number n1, Number n2) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    
     Class n1Class = n1.getClass();
     if (n1Class.isInstance(n2)) {
      Method compareTo = n1Class.getMethod("compareTo", n1Class);
      return (Integer) compareTo.invoke(n1, n2);
     }
    
     return -23;
    }
    

    This is since all non-Atomic Numbers implement Comparable

    EDIT:

    This is costly due to reflection: I know

    EDIT 2:

    This of course does not take of a case in which you want to compare decimals to ints or some such...

    EDIT 3:

    This assumes that there are no custom-defined descendants of Number that do not implement Comparable (thanks @DJClayworth)

提交回复
热议问题