-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInvokeMethod.java
75 lines (61 loc) · 1.98 KB
/
InvokeMethod.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package other;
import org.junit.jupiter.api.Test;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Method;
import java.util.function.Consumer;
public class InvokeMethod {
private static final InvokeMethod INSTANCE = new InvokeMethod();
public static final Class<? extends InvokeMethod> CLS = InvokeMethod.class;
/**
* 直接调用
*/
@Test
public void byInvoke() {
sayByStatic();
INSTANCE.sayByInstance();
}
/**
* Lambda / 方法引用
* 局限性较大
*/
@Test
public void byLambda() {
Runnable staticRunnable = InvokeMethod::sayByStatic;
Consumer<InvokeMethod> instanceConsumer = InvokeMethod::sayByInstance;
Runnable instanceRunnable = INSTANCE::sayByInstance;
staticRunnable.run();
instanceConsumer.accept(INSTANCE);
instanceRunnable.run();
}
/**
* 反射
*/
@Test
public void byReflect() throws Exception {
Method staticMethod = CLS.getDeclaredMethod("sayByStatic");
staticMethod.setAccessible(true);
Method instanceMethod = CLS.getDeclaredMethod("sayByInstance");
instanceMethod.setAccessible(true);
staticMethod.invoke(null);
staticMethod.invoke(INSTANCE);
}
/**
* 方法句柄
*/
@Test
public void byMethodHandle() throws Throwable {
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodHandle staticHandle = lookup.findStatic(CLS, "sayByStatic", MethodType.methodType(void.class));
MethodHandle instanceHandle = lookup.findVirtual(CLS, "sayByInstance", MethodType.methodType(void.class));
staticHandle.invoke();
instanceHandle.invoke(INSTANCE);
}
private static void sayByStatic() {
System.out.println("[static]hello world!");
}
private void sayByInstance() {
System.out.println("[instance]hello world!");
}
}