-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChangeField.java
86 lines (66 loc) · 2.2 KB
/
ChangeField.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
76
77
78
79
80
81
82
83
84
85
86
package other;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import sun.misc.Unsafe;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.lang.reflect.Field;
public class ChangeField {
/**
* 直接分配
*/
@Test
public void byAssign() {
Entry entry = new Entry();
entry.pubString = "assign";
Assertions.assertEquals("assign", entry.getPubString());
}
/**
* 反射
*/
@Test
public void byReflect() throws Exception {
Entry entry = new Entry();
Field field = entry.getClass().getDeclaredField("string");
field.setAccessible(true);
field.set(entry, "hack");
Assertions.assertEquals("hack", entry.getString());
}
/**
* 方法句柄
*/
@Test
public void byMethodHandle() throws Throwable {
Entry entry = new Entry();
MethodHandles.Lookup lookup = MethodHandles.privateLookupIn(Entry.class, MethodHandles.lookup());
MethodHandle methodHandle = lookup.findSetter(Entry.class, "string", String.class);
methodHandle.invokeExact(entry, "hack");
Assertions.assertEquals("hack", entry.getString());
}
/**
* 变量句柄
*/
@Test
public void byVarHandle() throws Exception {
Entry entry = new Entry();
MethodHandles.Lookup lookup = MethodHandles.privateLookupIn(Entry.class, MethodHandles.lookup());
VarHandle varHandle = lookup.findVarHandle(Entry.class, "string", String.class);
varHandle.set(entry, "hack");
Assertions.assertEquals("hack", entry.getString());
}
/**
* Unsafe
*/
@Test
public void byUnsafe() throws Exception {
Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
Unsafe unsafe = (Unsafe) unsafeField.get(null);
Entry entry = new Entry();
Field field = entry.getClass().getDeclaredField("string");
long offset = unsafe.objectFieldOffset(field);
unsafe.putObject(entry, offset, "hack");
Assertions.assertEquals("hack", entry.getString());
}
}