Created
March 13, 2012 21:37
-
-
Save douglasrodrigo/2031834 to your computer and use it in GitHub Desktop.
java_unsafe
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
import java.lang.reflect.Field; | |
import sun.misc.Unsafe; | |
import sun.reflect.FieldAccessor; | |
import sun.reflect.ReflectionFactory; | |
public class Teste { | |
static { | |
try { | |
setValor(Boolean.class, "TRUE", new Boolean(false)); | |
setValor(Boolean.class, "FALSE", new Boolean(true)); | |
} catch (Exception e) { | |
} | |
} | |
public static void main(String[] args) { | |
System.out.println(Boolean.valueOf(true)); | |
} | |
public static Unsafe getUnsafe() throws SecurityException, | |
NoSuchFieldException { | |
return (Unsafe) getValor(Unsafe.class, "theUnsafe"); | |
} | |
private static Object getValor(Object obj, String campo) | |
throws SecurityException, NoSuchFieldException { | |
FieldAccessor accessor = getAccessor(obj, campo); | |
return accessor.get(obj.getClass()); | |
} | |
@SuppressWarnings("deprecation") | |
private static void setValor(Object obj, String campo, Object valor) | |
throws SecurityException, NoSuchFieldException { | |
Field field = getField(obj, campo); | |
Unsafe unsafe = getUnsafe(); | |
Object base = unsafe.staticFieldBase(field); | |
int fieldOffset = unsafe.fieldOffset(field); | |
unsafe.putObject(base, fieldOffset, valor); | |
} | |
private static FieldAccessor getAccessor(Object obj, String campo) | |
throws SecurityException, NoSuchFieldException { | |
Field field = getField(obj, campo); | |
FieldAccessor accessor = ReflectionFactory.getReflectionFactory() | |
.newFieldAccessor(field, true); | |
return accessor; | |
} | |
private static Field getField(Object obj, String campo) | |
throws SecurityException, NoSuchFieldException { | |
Class<?> classe = obj.getClass(); | |
if (obj instanceof Class<?>) { | |
classe = (Class<?>) obj; | |
} | |
return classe.getDeclaredField(campo); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment