Last active
April 7, 2021 13:33
-
-
Save omidp/8d77ad9ab4af2f7bb83b2a16918c1219 to your computer and use it in GitHub Desktop.
instantiate without calling constructor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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