androidconstructorobjectinstantiation

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.


Solution

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