Java 动态代理

1、定义代理类接口PersonStudent
2、定义被代理类实现代理类接口Student
3、定义动态代理类DynamicProxy实现InvocationHandler接口,同时实现两个方法blind[获取被代理类对象]与invoke[关联被代理类方法]。。。。此类可以看成动态代理方法的必须
4、使用的时候,一次创建动态代理对象DynamicProxy;同时创建被代理类对象实例(可以多个);通过blind将被代理对象绑定到代理类对象实例(可以单个或者多个),通过代理类对象的方法调用被代理类对象方法

示例如下:

代理类接口PersonStudent
public interface PersonStudent{
String toString();
public void showMsg();
}
被代理类Student
package edu.hnu.ct;

public class Student implements PersonStudent{
int ID;
String School;
Person Leader;
public Student(int iD, String school, Person leader) {
ID = iD;
School = school;
Leader = leader;
}
@Override
public String toString() {
System.out.println(“Return Student ins>>”);
return “Student [ID=” + ID + “, School=” + School + “, Leader=” + Leader “+ “]”;
}

public void showMsg(){
    System.out.println(this.toString());
}

}

动态代理类
public class DynamicProxy implements InvocationHandler{
Object obj;
public Object blind(Object obj){
this.obj = obj;
return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO Auto-generated method stub
return method.invoke(obj, args);
}

}

测试过程:
@Test
public void testDynamicProxy(){
DynamicProxy dp = new DynamicProxy();
Student st = new Student(20, “Wuhan University”, null);
Student st1 = new Student(41, “Hunan University”, null);
Object obj = dp.blind(st);
PersonStudent p1 = (PersonStudent)obj;
p1.showMsg();

    obj = dp.blind(st1);
    p1 = (PersonStudent)obj;
    p1.showMsg();

}

你可能感兴趣的:(java,动态代理,学习)