Skip to content

Instantly share code, notes, and snippets.

@douglasrodrigo
Created March 13, 2012 22:48
Show Gist options
  • Save douglasrodrigo/2032371 to your computer and use it in GitHub Desktop.
Save douglasrodrigo/2032371 to your computer and use it in GitHub Desktop.
java allocate
public class ReflectionUtils {
public static <T> T allocate(Class<?> clazz) {
Object instance = null;
Object unsafe = getUnsafe();
Method allocate;
try {
allocate = unsafe.getClass().getDeclaredMethod("allocateInstance", Class.class);
instance = allocate.invoke(unsafe, clazz);
} catch (Exception e) {
throw new IllegalArgumentException("Not possible to instanciate " + clazz.getName());
}
return (T) instance;
}
private static Object getUnsafe() {
try {
Class<?> unsafeClass = Class.forName("sun.misc.Unsafe");
Field unsafeField = unsafeClass.getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
Object unsafeObj = unsafeField.get(unsafeClass);
return unsafeObj;
}
catch (Exception e) {
return null;//UNSAFE_ERROR_CODE;
}
}
}
public class Pessoa {
private Long id;
public Pessoa(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
public class Test {
public static void main(String[] args) {
System.out.println(allocate(Pessoa.class)); //Pessoa@1f
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment