Can constructors be circumvented when creating objects in Android?

Does Android have any way to create objects without calling any of its constructors?

In Java, Sun has sun.reflect.ReflectionFactory.getReflectionFactory (). newConstructorForSerialization () , in .Net we have System.Runtime.Serialization.FormatterServices.GetUninitializedObject () , but I could not find anything like it on the Android platform.

+6
android constructor
source share
4 answers

After examining the Android source code, we found a way to achieve this using the static method ObjectInputStream # newInstance ().

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); } 
+5
source share

You can do this from native code using the JNI AllocObject function. See JNI Spec . Calling your own code will be more expensive than calling the no-op constructor, but probably cheaper than calling the constructor that throws an exception.

I do not know if there is another way to do this. Nothing rushes at me.

+2
source share

I donโ€™t believe that, however the Android platform contains the Java Reflection API in java.lang.reflect.* , So everything that is possible using the Java Reflection API is possible in Android

0
source share

I found a library that can handle OBJ init bypassing the constructor http://objenesis.org/index.html And they have different methods for different APIs. There is a slight difference in their APIs 17 and 18+, as in the current proposed answer. Also, Android N + uses something called Unsafe, which should be implemented by the new JVM http://mishadoff.com/blog/java-magic-part-4-sun-dot-misc-dot-unsafe/

0
source share

All Articles