LetsCoding.cn

天地之间有杆秤,拿秤砣砸老百姓。

Java动态代理测试代码

 

 1import java.lang.reflect.InvocationHandler;
 2import java.lang.reflect.Method;
 3import java.lang.reflect.Proxy;
 4
 5import junit.framework.TestCase;
 6
 7interface Human {
 8    public String getName();
 9    public int getId();
10    public void printNameAndId();
11}

12
13class Student implements Human {
14    private String name;
15    private int id;
16
17    public Student(int id, String name) {
18        this.id = id;
19        this.name = name;
20    }

21
22    public String getName() {
23        return name;
24    }

25    
26    public int getId(){
27        return id;
28    }

29    
30    public void printNameAndId() {
31        System.out.println("name: " + name);
32        System.out.println("id: " + id);
33    }

34}

35
36class MyInvocationHandler implements InvocationHandler {
37    private Object o;    // 被代理的对象
38
39    public Object newProxy(Object targetObject) {
40        this.o = targetObject;
41
42        // 返回代理实例
43        return Proxy.newProxyInstance(o.getClass().getClassLoader(), o
44                .getClass().getInterfaces(), this);
45    }

46
47    @Override
48    public Object invoke(Object proxy, Method method, Object[] args)
49            throws Throwable {
50        aspectLogic(); // 切面逻辑
51        Object ret = method.invoke(o, args);
52        //aspectLogic(); // 切面逻辑
53        return ret;
54    }

55
56    private void aspectLogic() {
57        System.out.println("这里放入横切性逻辑");
58    }

59}

60
61public class ProxyClassTest extends TestCase {
62    private Student s;
63    private MyInvocationHandler handler;
64    private Human h;
65    
66    @Override
67    public void setUp() {    
68        s = new Student(10"小剑");
69        handler = new MyInvocationHandler();
70        h = (Human) handler.newProxy(s);
71    }

72
73    public void testGetName() {
74        String n = h.getName();
75        System.out.println(n);
76    }

77
78    public void testPrintNameAndId() {    
79        h.printNameAndId();
80    }

81}

82

posted on 2009-10-10 09:19 Rolandz 阅读(299) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

留言簿(1)

随笔分类(12)

随笔档案(19)

积分与排名

最新评论

阅读排行榜

评论排行榜