Skip to content

Instantly share code, notes, and snippets.

@douglasrodrigo
Created March 13, 2012 21:37
Show Gist options
  • Save douglasrodrigo/2031834 to your computer and use it in GitHub Desktop.
Save douglasrodrigo/2031834 to your computer and use it in GitHub Desktop.
java_unsafe
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