jdk动态代理使用InvocationHandler实现,最终生成的代理类是:
public final class $Proxy0 extends Proxy implements Subject {
}
首先明白动态代理类是静态代理的加强版本, 不用每次增加实现一个接口而写多个代理类,
动态代理简而言之,就是对于一个对象,在调用其方法时,能够附加的做些其他操作而产生的。
1,通过Proxy.newProxyInstance生成的代理类,执行接口里的方法,实际上是调用了InvocationHandler 的
invoke方法。
2,InvocationHandler需要用户自定义,在invoke方法里执行method.invoke(subject, args),用来执行目标对象里参数为args的方法method,故InvocationHandler才是真正的被代理类的直接访问者。
3,代理类继承了Proxy,由于对象的单继承性质,所以代理类不能再继承其他类,所以JDK的动态代理只支持接口的方式代理,并不能支持具体实现类的代理。
自己想法:用Proxy.newProxyInstance生成的代理类对象(通过类加载器和接口得到代理类,再得到构造方法 实例化对象),那就需要InvocationHandler 类作为中间桥梁得到调用接口的子类对象和方法。
1.Proxy.newProxyInstance(1.....,2....,handler)通过handler得到代理类有这个参数的构造,然后通过这个构造实例化代理类对象
2.代理类对象调用接口里的方法,将方法参数和该方法传入handler的invoke方法。
下面看一段代码
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.SQLOutput;
public interface Subject {
void eat(Integer num,String msg);
}
interface WWWWW{
void wwwww();
}
class RealSubject implements Subject,WWWWW{
@Override
public void eat(Integer num, String msg) {
System.out.println(num+"份"+msg);
}
@Override
public void wwwww() {
System.out.println("我很开心");
}
}
class RealSubjectHandle implements InvocationHandler{
private Object target;
public RealSubjectHandle(Object target){
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("前");
Object ret = method.invoke(target,args);
System.out.println("后");
return ret;
}
}
class Test{
public static void main(String[] args) {
Subject subject = new RealSubject();
InvocationHandler handler = new RealSubjectHandle(subject);
WWWWW sss = (WWWWW) Proxy.newProxyInstance(subject.getClass().getClassLoader(),
// subject.getClass().getInterfaces(),
new Class[]{Subject.class,WWWWW.class},
handler);
sss.wwwww();
}
}