-
Enhancement
-
Resolution: Unresolved
-
P4
-
None
-
1.4.2
-
x86
-
windows_xp
Name: rmT116609 Date: 10/17/2003
A DESCRIPTION OF THE REQUEST :
It should be possible to create an instance of a class via reflection without calling any of the declared or implicit constructors of the class. All fields of the instance should be initialized to null values.
This would enable custom serialization using reflection. It is currently possible on Sun's JDK 1.4.2 using undocumented features.
JUSTIFICATION :
The funtionality is required for implementing custom serialization via the reflection api. Existing custom XML serialization APIs rely on standard serialization and convert the streams to the desired format.
I tried to create a serialization mechanism using reflection, and failed at this point. Creating classes using any of their declared constructors may always have unexpected side effects.
Additionally, the feature would make it possible to implemented serialization in standard classes. It would reduce the size of the core vm.
EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
A method that creates the desired instance should be added to java.lang.Class.
ACTUAL -
I used a debugger to reverse engineer the inner workings of java object serialization and finally came up with this code:
public Object createInstance(Class c) throws Throwable {
Constructor constructor=Object.class.getDeclaredConstructor(new Class[0]);
constructor=ReflectionFactory.getReflectionFactory().newConstructorForSerialization(c, constructor);
constructor.setAccessible(true);
return constructor.newInstance(new Object[0]);
}
But this code relies on undocumented features and may fail on several JREs.
CUSTOMER SUBMITTED WORKAROUND :
Maybe a serialized stream containing the desired empty instance can be created by hand and then read.
(Incident Review ID: 200409)
======================================================================
- relates to
-
JDK-6220682 (reflect) Object creation without calling constructors or field initialisation
- Closed