views:

119

answers:

3

Do Android have any way to instantiate objects without calling any of its constructors?

In Java, Sun have sun.reflect.ReflectionFactory.getReflectionFactory().newConstructorForSerialization(), in .Net we have System.Runtime.Serialization.FormatterServices.GetUninitializedObject() but I was not able to find anything like that in the Android platform.

A: 

I don't believe so, however the Android platform does contain the Java Reflection API in java.lang.reflect.* so anything that is possible using the Java Reflection API is possible in Android

chrisbunney
Indeed, I noticed that package but as I said, I could not find anything to achieve my goal :(
Vagaus
+2  A: 

You can do this from native code with the JNI AllocObject function. See the JNI Spec. Calling out to native code is going to be more expensive than calling a no-op constructor, but probably cheaper than calling a constructor that throws an exception.

I don't know if there's another way to do it. Nothing is leaping out at me.

fadden
+1  A: 

Hi.

After looking into Android source code we found a way to achieve this by using ObjectInputStream#newInstance() static method.

private Object newInstanceSkippingConstructor(final Class clazz) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,     InvocationTargetException {

    Method newInstance = ObjectInputStream.class.getDeclaredMethod("newInstance", Class.class, Class.class);
    newInstance.setAccessible(true);
    return newInstance.invoke(null, clazz, Object.class);

}
Vagaus