[JavaSpecialists 175] - Creating Objects Without Calling Constructors
import sun.reflect.ReflectionFactory;
import java.lang.reflect.Constructor;
public class SilentObjectCreator {
public staticT create(Class clazz) {
return create(clazz, Object.class);
}
public staticT 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);
}
}
}