50,528
社区成员
发帖
与我相关
我的任务
分享
public interface Sourcable {
public void go();
}
public class Source implements Sourcable {
public void go() {
System.out.println("Source method go()");
}
}
public class Decorator implements Sourcable {
private Sourcable sourcable;
public Decorator(Sourcable sourcable){
this.sourcable = sourcable;
}
public void go() {
//这里可以有你的处理
sourcable.go();
//这里可以有你的处理
}
}
public class ObjectDynamicProxy implements InvocationHandler{
//真实对象引入
private Object proxyObj;
public void setObj(Object obj) {
this.proxyObj = obj;
}
public ObjectDynamicProxy(Object obj){
this.proxyObj = obj;
}
public Object invoke(Object object, Method method, Object[] args)
throws Throwable {
System.out.println("before dynamic proxy method.");
Object obj = method.invoke(proxyObj, args);
System.out.println("after dynamic proxy method.");
return obj;
}
/**
* 代理对象生产工厂
* @param obj
* @return
*/
public static Object factory(Object obj) {
//获取传入对象的Class对象
Class<?> classType = obj.getClass();
//生成代理对象并返回
//该对象实现传入对象所实现的接口
//生成的代理对象的所有方法都由第三个参数的invoke方法来接管和调用
return Proxy.newProxyInstance(classType.getClassLoader(), classType
.getInterfaces(), new ObjectDynamicProxy(obj));
}
}
public class Client {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
//通过代理对象生成工厂生成该代理对象
List list = (List)ObjectDynamicProxy.factory(new ArrayList());
list.add("hello");
}
}