获取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;
}
}