Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to bypass constructors when instantiating objects in Android

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.

like image 295
Vagaus Avatar asked Jun 25 '10 21:06

Vagaus


2 Answers

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);

}
like image 64
Vagaus Avatar answered Oct 21 '22 08:10

Vagaus


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.

like image 36
fadden Avatar answered Oct 21 '22 09:10

fadden