基于接口的动态代理就是Proxy的返回值,之后在执行方法的时候,就是在执行invoke方法,而不是执行它本身实现类里面的方法!!!
是不是很神奇??没办法,谁让这个返回值是动态代理的返回值呢!!
public class beanFactory {
public static void main(String[] args) {
Istudent student = new Student();//Student是接口Istudent的实现类
Istudent proxyStu = (Istudent)Proxy.newProxyInstance(Istudent.class.getClassLoader(), new Class[]{Istudent.class}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object obj = null;
if(method.getName().equals("name")){
method.invoke(student,args)
}
System.out.println("hello world");
return obj;
}
});
proxyStu.name();// 调用age的时候,必须得按照invoke里面的方法来,因为这个stu是动态代理的返回值
}
}
===============================
public interface Istudent {
public void name();
}
====================================
public class IstudentImpl implements Istudent {
@Override
public void name() {
System.out.println("我叫james");
}
}