代理接口Subject
package proxy;
public interface Subject {
String say(String name);
}
被代理的类
package proxy;
public class RealSubject implements Subject {
@Override
public String say(String name) {
return name;
}
}
实现InvocationHandler接口完成代理
package proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class MyInvocationHandler implements InvocationHandler {
private Object object;
//动态绑定要被代理的类
public Object bind(Object object) {
System.out.println("这是代理类");
this.object = object;
return Proxy.newProxyInstance(object.getClass().getClassLoader(),
object.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("代理开始");
return method.invoke(this.object, args);
}
public static void main(String[] args) {
MyInvocationHandler myInvocationHandler=new MyInvocationHandler();
Subject subject = (Subject) myInvocationHandler.bind(new RealSubject());
System.out.println(subject.say("hello"));
}
}
参考博文http://www.cnblogs.com/rollenholt/archive/2011/09/02/2163758.html#undefined
1122

被折叠的 条评论
为什么被折叠?



