Reflection操作Unsafe
2538 ワード
Reflectionを取得する2つの方法、詳細はコードを参照(Marked here.2011/11/12夜)
package com.myjdk.helper;
import java.lang.reflect.Field;
import sun.misc.Unsafe;
import junit.framework.TestCase;
public class TestUnsafeSupport extends TestCase {
private static Unsafe unsafe;
private static Person person;
protected void setUp() throws Exception {
Field field = null;
try {
field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
unsafe = (Unsafe) field.get(null);
} catch (Exception ex) {
ex.printStackTrace();
}
person = new Person();
}
/**
* Reflection java.lang.reflect.*
*/
public void testOrdinaryReflection() {
try {
Class<?> personClazz = Person.class;
Field __ageField = personClazz.getDeclaredField("age");
assertEquals(0, __ageField.getInt(person));
__ageField.set(person, 5);
assertEquals(5, __ageField.getInt(person));
} catch (Exception ex) {
fail(ex.getLocalizedMessage());
}
}
/**
* sun.mic.Unsafe Reflection 、
*
*
*/
public void testUnsafeReflection() {
try {
// field class
long ageOffset = unsafe.objectFieldOffset(Person.class.getDeclaredField("age"));
// getInt
// unsafe.getInt(long), long
// offset ,JVM
assertEquals(0, unsafe.getInt(person, ageOffset));
// cas
// public native boolean compareAndSwapInt(Object obj, long offset, int expect, int update);
unsafe.compareAndSwapInt(person, ageOffset, 0, 25);
unsafe.compareAndSwapInt(person, ageOffset, 12, 36);
assertEquals(25, unsafe.getInt(person, ageOffset));
unsafe.putInt(person, ageOffset, 0);
assertEquals(0, unsafe.getInt(person, ageOffset));
// unsafe.putIntVolatile();
} catch (Exception ex) {
fail(ex.getLocalizedMessage());
}
}
}
class Person {
String name;
int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}