介绍一下使用jdk实现动态代理
public interface ISubject {
void execute();
}
public class ISubjectImpl implements ISubject {
public void execute() {
System.out.println("execute ISubjectImpl");
}
}
public class CustomizeHandle implements InvocationHandler {
private Object target;
public CustomizeHandle(Object proxied) {
this.target = proxied;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
this.before();
System.out.println("proxy class :" + proxy.getClass());
System.out.println("arg : "+Arrays.toString(args));
System.out.println("method : "+method.getName());
Object result = method.invoke(target , args);
this.after();
return result;
}
private void before() {
System.out.println("handle before");
}
private void after() {
System.out.println("handler after");
}
}
public class TestCustomizeHandle {
public static void main(String[] args) {
ClassLoader classLoader = ISubject.class.getClassLoader();
CustomizeHandle customizeHandle = new CustomizeHandle(new ISubjectImpl());
ISubject iSubject = (ISubject)Proxy.newProxyInstance(classLoader,
new Class[]{ISubject.class}, customizeHandle);
iSubject.execute();
}
}
输出结果:
handle before
proxy class :class com.sun.proxy.$Proxy0
arg : null
method : execute
execute ISubjectImpl
handler after