ProxyFactory类
package com.zzq.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyFactory implements InvocationHandler{
private Object target;
public ProxyFactory() {}
public void setTarget(Object target) {
this.target = target;
}
public Object createProxyBean() {
return Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
this
);
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = null;
try {
this.before();
result = method.invoke(target, args);
this.afert();
} catch (Exception e) {
afterThrow(e);
}
return result;
}
public void before() {
System.out.println("before");
}
public void afert() {
System.out.println("afert");
}
public void afterThrow(Throwable t) {
System.out.println("afterThrow");
if(t instanceof InvocationTargetException) {
t = t.getCause();
System.out.println(t.getMessage());
} else {
System.out.println(t.getMessage());
}
}
}
package com.zzq.proxy;
public interface SimpleBean {
public void sayHello();
public void throwException();
}
package com.zzq.proxy;
public class SimpleBeanImpl implements SimpleBean {
public void sayHello() {
System.out.println("hello proxy pattern!");
}
public void throwException() {
throw new RuntimeException("出错了");
}
public static void main(String[] args) {
ProxyFactory factory = new ProxyFactory();
factory.setTarget(new SimpleBeanImpl());
SimpleBean proxy = (SimpleBean)factory.createProxyBean();
proxy.sayHello();
proxy.throwException();
}
}