Reflection 操作 Unsafe

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值