方法呼叫之靜態分派與動態分派
阿新 • • 發佈:2019-02-13
靜態分派與動態分派
靜態分派
自動轉型按照 char > int > long > float > double
如下面案例所示:
public class Test {
public static void sayHello(char arg) {
System.out.println("hello char");
}
public static void sayHello(int arg) {
System.out.println("hello int");
}
public static void sayHello(long arg) {
System.out.println("hello long");
}
public static void sayHello(Character arg) {
System.out.println("hello Character");
}
public static void main(String[] args) {
sayHello('a');
}
}
動態分派
如下面案例所示:
public class MethodHandleTest {
public static class ClassA{
public void println(String s){
System.out.println(s + ".ClassA");
}
}
public static void main(String[] arge) {
Object obj = System.currentTimeMillis() % 2 == 0 ? System.out : new ClassA();
//
try {
getPlantMH(obj).invokeExact("hello" );
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
private static MethodHandle getPlantMH(Object reveiver) throws NoSuchMethodException, IllegalAccessException {
MethodType mt = MethodType.methodType(void.class, String.class);
return lookup().findVirtual(reveiver.getClass(), "println", mt).bindTo(reveiver);
}
}