JDK-4939842 : (reflect) Reflection should create classes without calling constructor
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.lang:reflect
  • Affected Version: 1.4.2
  • Priority: P4
  • Status: Open
  • Resolution: Unresolved
  • OS: windows_xp
  • CPU: x86
  • Submitted: 2003-10-17
  • Updated: 2012-09-28
Related Reports
Relates :  
Description

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