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
|
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.Arrays;
import java.util.List;
public class JVMMethodInstruction implements Runnable {
static {
System.out.println("<clinit>");
}
{
System.out.println("<init block>");
}
public JVMMethodInstruction() {}
static void staticMethod() {}
static void staticForMethodHandle(String str) {}
private void privateMethod() {}
void instanceMethod() {}
public void forMethodHandle(String str) {}
@Override
public void run() {}
public static void main(String[] args) throws Throwable {
/**
* invoke special
*/
JVMMethodInstruction test = new JVMMethodInstruction();
/**
* invoke special
*/
test.privateMethod();
/**
* invoke virtual
*/
test.instanceMethod();
/**
* invoke static
*/
staticMethod();
/**
* invoke interface
*/
Runnable r = test;
r.run();
/**
* invoke dynamic instance method
*/
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodHandle mh = lookup
.findVirtual(JVMMethodInstruction.class, "forMethodHandle",
MethodType.methodType(void.class, String.class));
System.out.println(mh);
mh.bindTo(test).invoke("a");
/**
* invoke dynamic static method
*/
mh = lookup.findStatic(JVMMethodInstruction.class, "staticForMethodHandle",
MethodType.methodType(void.class, String.class));
mh.invoke("static");
/**
* Java 8中,lambda表达式和默认方法时,底层会生成和使用invoke dynamic
* invoke dynamic
*/
List<Integer> list = Arrays.asList(1, 2, 3, 4);
list.stream().forEach(System.out::println);
}
}
|
评论