Skip to content

Commit ef322bf

Browse files
committed
msgpack#101: Workaround for Android OS. Creating Unsafe instance by calling its constructor
1 parent 0cbcf66 commit ef322bf

File tree

1 file changed

+13
-4
lines changed

1 file changed

+13
-4
lines changed

msgpack-core/src/main/java/org/msgpack/core/buffer/MessageBuffer.java

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,22 @@ public class MessageBuffer {
2929
static {
3030
try {
3131
// Fetch theUnsafe object for Orackle JDK and OpenJDK
32-
Field field = Unsafe.class.getDeclaredField("theUnsafe");
33-
field.setAccessible(true);
34-
unsafe = (Unsafe) field.get(null);
32+
Unsafe u;
33+
try {
34+
Field field = Unsafe.class.getDeclaredField("theUnsafe");
35+
field.setAccessible(true);
36+
u = (Unsafe) field.get(null);
37+
}
38+
catch(NoSuchFieldException e) {
39+
// Workaround for Unsafe instance for Android
40+
Constructor<Unsafe> unsafeConstructor = Unsafe.class.getDeclaredConstructor();
41+
unsafeConstructor.setAccessible(true);
42+
u = (Unsafe) unsafeConstructor.newInstance();
43+
}
44+
unsafe = u;
3545
if (unsafe == null) {
3646
throw new RuntimeException("Unsafe is unavailable");
3747
}
38-
// TODO Finding Unsafe instance for Android JVM
3948

4049
ARRAY_BYTE_BASE_OFFSET = unsafe.arrayBaseOffset(byte[].class);
4150
ARRAY_BYTE_INDEX_SCALE = unsafe.arrayIndexScale(byte[].class);

0 commit comments

Comments
 (0)