-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathUnsafeTools.java
More file actions
39 lines (32 loc) · 1.06 KB
/
UnsafeTools.java
File metadata and controls
39 lines (32 loc) · 1.06 KB
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
package bwapi;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
import java.nio.Buffer;
class UnsafeTools {
private static Object getOrCrash(final Class<?> className, final Object object, final String fieldName) {
try { // get
final Field field = className.getDeclaredField(fieldName);
final boolean accessible = field.isAccessible();
if (!accessible) {
field.setAccessible(true);
}
final Object result = field.get(object);
if (!accessible) {
field.setAccessible(false);
}
return result;
} catch (final Exception e) { // or crash...
throw new RuntimeException(e);
}
}
static Unsafe getUnsafe() {
return (Unsafe) getOrCrash(Unsafe.class, null, "theUnsafe");
}
/**
* Alternative to `((DirectBuffer) buffer).address())`
* (ab)using reflection
*/
static long getAddress(final Buffer buffer) {
return (long) getOrCrash(Buffer.class, buffer, "address");
}
}