jdk的动态代理调用了Proxy.newProxyInstance(ClassLoader loader,Class<?>[]interfaces,InvocationHandler h) 方法。
通过该方法生成字节码,动态的创建了一个代理类,interface参数是该动态类所继承的所有接口, 而继承InvocationHandler
接口的类则是实现在调用代理接口方法前后的具体逻辑
package com.icar.designModel;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class JdkProxy {
/*
* jdk的动态代理调用了Proxy.newProxyInstance(ClassLoader loader,Class<?>[]
* interfaces,InvocationHandler h) 方法。
* 通过该方法生成字节码,动态的创建了一个代理类,interface参数是该动态类所继承的所有接口, 而继承InvocationHandler
* 接口的类则是实现在调用代理接口方法前后的具体逻辑,下边是具体的实现:
*/
static interface Base{
void sing();
void sleep();
}
static class BaseImpl implements Base{
@Override
public void sing() {
// TODO Auto-generated method stub
System.out.println("sing");
}
@Override
public void sleep() {
// TODO Auto-generated method stub
System.out.println("sleep");
}
}
//代理类,(用此对象代理Base类)
static class ProxyInvocationHandler implements InvocationHandler{
private Base target;
public ProxyInvocationHandler(Base target) {
this.target=target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("GG");
return method.invoke(target, args);
}
}
public static void main(String[] args) {
Base base = new BaseImpl();
Base baseProxy = (Base) Proxy.newProxyInstance(base.getClass().getClassLoader(),base.getClass().getInterfaces(), new ProxyInvocationHandler(base));
baseProxy.sing();
baseProxy.sleep();
}
}