Android 是否有任何方法可以在不调用任何构造函数的情况下实例化对象?
在 Java 中,Sun 有 sun.reflect.ReflectionFactory.getReflectionFactory().newConstructorForSerialization(),在 .Net 中我们有 System.Runtime.Serialization.FormatterServices.GetUninitializedObject() 但我在 Android 平台上找不到类似的东西。
最佳答案
在查看 Android 源代码后,我们找到了一种通过使用 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);
}
关于android - 在Android中实例化对象时是否可以绕过构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3121515/