玩转Java泛型(Fun with Java generics)

2019-10-17 14:10发布

任何人都知道如何写下面使用泛型,避免编译器警告的代码段? (@SuppressWarnings( “未登记”)被认为是作弊)。

而且,也许,经由类型“左”仿制药检查是一样的“正确”的类型?

public void assertLessOrEqual(Comparable left, Comparable right) {
    if (left == null || right == null || (left.compareTo(right) > 0)) {
        String msg = "["+left+"] is not less than ["+right+"]";
        throw new RuntimeException("assertLessOrEqual: " + msg);
    }
}

Answer 1:

这适用于可比类型太多的子类:

public <T extends Comparable<? super T>> void assertLessOrEqual(T left, T right) {
  if (left == null || right == null || left.compareTo(right) > 0) {
    String msg = "["+left+"] is not less than ["+right+"]";
    throw new RuntimeException("assertLessOrEqual: " + msg);
  }
}


Answer 2:

这个怎么样:

public <T extends Comparable<T>> void assertLessOrEqual(T left, T right) {
  if (left == null || right == null || (left.compareTo(right) > 0)) {
    String msg = "["+left+"] is not less than ["+right+"]";
    throw new RuntimeException("assertLessOrEqual: " + msg);
  }
}

这也许可以做出更一般的一点点 ,但只能通过使它更加复杂了:)



Answer 3:

您不能通过泛型检查的“左”的类型是一样的“正确”在运行时类型。 Java泛型是通过实现类型擦除 ,所以对一般类型参数的信息在运行时丢失。

public <T extends Comparable<T>> void assertLessOrEqual(T left, T right) {
    if (left == null || right == null || (left.compareTo(right) > 0)) {
        String msg = "["+left+"] is not less than ["+right+"]";
        throw new RuntimeException("assertLessOrEqual: " + msg);
    }
}


文章来源: Fun with Java generics