Skip to content

Instantly share code, notes, and snippets.

@omidp
Last active April 7, 2021 13:33
Show Gist options
  • Save omidp/8d77ad9ab4af2f7bb83b2a16918c1219 to your computer and use it in GitHub Desktop.
Save omidp/8d77ad9ab4af2f7bb83b2a16918c1219 to your computer and use it in GitHub Desktop.
instantiate without calling constructor
public class CreationTest {
public static void main(String[] args) {
// Creating MySerializable by calling NotSerializable no-args
// constructor, but not the MySerializable constructor.
MySerializable ms = SilentObjectCreator.create(
MySerializable.class, NotSerializable.class);
System.out.println("ms = " + ms);
// Creating MySerializable by not calling any constructors.
MySerializable ms2 = SilentObjectCreator.create(
MySerializable.class
);
System.out.println("ms2 = " + ms2);
}
}
import sun.reflect.ReflectionFactory;
import java.lang.reflect.Constructor;
public class SilentObjectCreator {
public static <T> T create(Class<T> clazz) {
return create(clazz, Object.class);
}
public static <T> T create(Class<T> clazz,
Class<? super T> parent) {
try {
ReflectionFactory rf =
ReflectionFactory.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);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment