定义真实类:
public class Message {
public void print(){
System.out.println("发送消息");
}
}
定义代理类:
定义代理类,实现MethodInterceptor接口,实现动态代理
public class ProxySubject implements MethodInterceptor {
private Object obj;
public ProxySubject(Object obj){
this.obj=obj;
}
public void ready(){
System.out.println("打开电脑");
}
public void over(){
System.out.println("关闭电源");
}
@Override
public Object intercept(Object obj, Method method, Object[] arg, MethodProxy arg3) throws Throwable {
this.ready();
Object ret=method.invoke(this.obj, arg);
this.over();
return ret;
}
}
定义测试类:
ublic class Test {
public static void main(String[] args) {
Message msg=new Message();
Enhancer enhancer=new Enhancer(); //负责代理关系操作的类
enhancer.setSuperclass(msg.getClass()); //传入真实对象
enhancer.setCallback(new ProxySubject(msg));//传入代理对象
Message temp=(Message) enhancer.create();
temp.print();
}
}