Java静态多态(重载)和泛型之间的继承

标签 java generics java-11 overload-resolution static-polymorphism

Java 11(可能无关紧要):

public static String toString(Object obj) {
    return ReflectionToStringBuilder.toString(obj, ToStringStyle.SHORT_PREFIX_STYLE);
}

public static String toString(Collection<Object> collection) {
    return collection.stream()
            .map(SaLogUtils::toString)
            .collect(Collectors.joining(", ", "[", "]"));
}

public static void main(String[] args) {
    List<Integer> list = List.of(Integer.valueOf(1));
    System.out.println(SaLogUtils.toString(list));
    System.out.println(SaLogUtils.toString(List.of(Integer.valueOf(1))));
}

令人惊讶的输出:
// from toString(Object)
ImmutableCollections.List12[e0=1,e1=<null>]
// from toString(Collection<Object>)
[Integer[value=1]]

为什么Java静态选择不同的方法?

最佳答案

当可以调用多个重载时,Java 选择 the most specific applicable method :

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time error. In cases such as an explicitly typed lambda expression argument (§15.27.1) or a variable arity invocation (§15.12.2.4), some flexibility is allowed to adapt one signature to the other.


toString(Collection<Object>)不适用于 List<Integer> , 因为 a List<Integer> isn't a List<Object> ,所以它不是 Collection<Object>任何一个。因此,只有 toString(Object)方法是适用的,所以这就是被调用的方法。
toString(Collection<Object>)适用于 List.of(someInteger)因为那 List.of是一个多表达式:它可能是 List<Integer> ,可能是 List<Object> ,可能是 List<Serializable> .

由于两者 toString(Object)toString(Collection<Object>)是适用的,它必须选择其中之一(或声明不明确)。 Collection重载更具体,因为:
  • 您传递给 toString(Collection<Object>) 的任何信息也可转至toString(Object)
  • 但是有些事情你可以传递给 toString(Object)不能传递给 toString(Collection<Object>) (例如 new Object() )。

  • 这使得 toString(Collection<Object>)更具体,所以这是一个被选择的。

    关于Java静态多态(重载)和泛型之间的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60059066/

    相关文章:

    c# - 区分重载的泛型方法和非泛型方法

    java - log4j2 与 Java 11 兼容吗?

    java - 如何构建使用java11的docker镜像

    java - 理论-Java-抽象数据类型和引用数据类型

    java - 通过 JCO 连接到 SAP 消息服务器

    java - 当返回类型只是 int 时,如何返回多个整数?

    generics - 有没有办法解决 Java 无法将泛型参数转发给非泛型类型的问题?

    generics - JavaFX 构建器/Java 泛型

    gradle - 使用 Java 11 运行 Sonar Scanner 时主版本号错误

    Java线程输出数据到集合得到错误的结果