12 September 2009

Creating Objects Without Calling Constructors

[JavaSpecialists 175] - Creating Objects Without Calling Constructors
import sun.reflect.ReflectionFactory;
import java.lang.reflect.Constructor;

public class SilentObjectCreator {
public static T create(Class clazz) {
return create(clazz, Object.class);
}

public static T create(Class clazz, Class parent) {
try {
ReflectionFactory rf = getReflectionFactory();
Constructor objDef = parent.getDeclaredConstructor();
Constructor intConstr = rf.newConstructorForSerialization(clazz, objDef);
return clazz.cast(intConstr.newInstance());
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException("Cannot create object", e);
}
}
}