为什么要调用这个重载方法而不是更具体?

use*_*089 2 java overloading

我试图理解为什么下面的代码总是调用"out(Object)"方法而不是更具体的"out(int | String)"方法.非常感谢解释和解决方法.

public static void main(String[] args) {
   Object[] objs = new Object[]{1, 2, 3, "test1", "test2", "test3", 1000L};
   for (Object o : objs) {
      out(o.getClass().cast(o)); // I have also tried passing 'o' directly 
                                 // rather than casting, but that still results 
                                 // in the out(Object) method being called
   }
}

private static void out(int value) {
   System.out.println("integer: " + value);
}

private static void out(String value) {
   System.out.println("string : " + value);
}

private static void out(Object value) {
   System.out.println("object : " + value);
}
Run Code Online (Sandbox Code Playgroud)

SLa*_*aks 5

重载解析始终在编译时发生.编译时类型o和方法的结果cast()Object,因此它调用了重载.