Created
March 13, 2012 22:48
-
-
Save douglasrodrigo/2032371 to your computer and use it in GitHub Desktop.
java allocate
This file contains 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 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