From 5ec289ff9d839644f2548ab21d98dbd000cc1722 Mon Sep 17 00:00:00 2001 From: Xizhi Zhu Date: Fri, 8 Apr 2016 14:29:13 +0300 Subject: [PATCH] Added support for pre-Gingerbread. --- .../java/com/squareup/moshi/ClassFactory.java | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/moshi/src/main/java/com/squareup/moshi/ClassFactory.java b/moshi/src/main/java/com/squareup/moshi/ClassFactory.java index 01a8170..48a4212 100644 --- a/moshi/src/main/java/com/squareup/moshi/ClassFactory.java +++ b/moshi/src/main/java/com/squareup/moshi/ClassFactory.java @@ -15,6 +15,7 @@ */ package com.squareup.moshi; +import java.io.ObjectInputStream; import java.io.ObjectStreamClass; import java.lang.reflect.Constructor; import java.lang.reflect.Field; @@ -77,7 +78,7 @@ abstract class ClassFactory { // Not the expected version of the Oracle Java library! } - // Try Dalvik/libcore's ObjectStreamClass mechanism. + // Try (post-Gingerbread) Dalvik/libcore's ObjectStreamClass mechanism. // public class ObjectStreamClass { // private static native int getConstructorId(Class c); // private static native Object newInstance(Class instantiationClass, int methodId); @@ -107,6 +108,27 @@ abstract class ClassFactory { // Not the expected version of Dalvik/libcore! } + // Try (pre-Gingerbread) Dalvik/libcore's ObjectInputStream mechanism. + // public class ObjectInputStream { + // private static native Object newInstance( + // Class instantiationClass, Class constructorClass); + // } + try { + final Method newInstance = ObjectInputStream.class.getDeclaredMethod( + "newInstance", Class.class, Class.class); + newInstance.setAccessible(true); + return new ClassFactory() { + @SuppressWarnings("unchecked") + @Override public T newInstance() throws InvocationTargetException, IllegalAccessException { + return (T) newInstance.invoke(null, rawType, Object.class); + } + @Override public String toString() { + return rawType.getName(); + } + }; + } catch (Exception ignored) { + } + throw new IllegalArgumentException("cannot construct instances of " + rawType.getName()); } }