- proxy动态代理 demo
//接口
public interface Student {
void getStudentName();
void getStudentAge();
}
//实行接口
public class JuniorStudent implements Student {
public void getStudentName() {
System.out.println(“my name is king”);
}
public void getStudentAge() {
System.out.println(“my age is 20”);
}
}
//代理类
/实现InvocationHandler/
public class ProxStudent implements InvocationHandler {
private Student student;
//创建构造方法赋值
public ProxStudent(Student student) {
this.student = student;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println(“my is proxyStudy”);
/获取所以代理接口的 方法/
method.invoke(student,args);
//获取代理类的某一个方法
// student.getStudentName();
System.out.println(“after”);
return student;
}
}
public class Client {
public static void main(String[] args) {
//获取代理的对象
Student student = new JuniorStudent();
//把要代理的对象 传进去 然后获取方法
InvocationHandler handlerStudent =new ProxStudent(student);
/*Proxy.newProxyInstance 创建代理对象
* handler.getClass().getClassLoader() 加载对象
* student.getClass().getInterfaces()获取代理的接口
* handlerStudent 将代理对象Student 关联到 handlerStudent上
* */
Student newProxyInstance = (Student) Proxy.newProxyInstance(handlerStudent.getClass()
.getClassLoader(),student.getClass().getInterfaces(),handlerStudent);
newProxyInstance.getStudentAge();
}
//创建class字节码文件 可以放在target 查看代码
try {
byte[] bytes = ProxyGenerator.generateProxyClass("$ProxyKing",new Class[]{Student.class});
FileOutputStream fileOutputStream = new FileOutputStream("D:/env/$ProxyKing.class");
fileOutputStream.write(bytes);
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
-
proxy 源码
Proxy.newProxyInstance{
//代理类的缓存
1. proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
ProxyClassFactory{
//在WeakCache的构造方法里 去调用
apply(){
interfaceClass = Class.forName(intf.getName(), false, loader);
//根据包名类名创建代理
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);{
ProxyGenerator var3 = new ProxyGenerator(var0, var1, var2);
final byte[] var4 = var3.generateClassFile();//创建class 文件返回数组 class也是字节码文件 上吗demo 有
defineClass0();{//需要吧 byte[]转为class 文件装进jvm 里面
用native 的方法 //本地方法
}
}
}
}//如果指定的加载器实现了指定的接口,这将简单地返回缓存的副本;//否则,它将通过ProxyClassFactory创建代理类
-
Class<?> cl = getProxyClass0(loader, intfs){
return proxyClassCache.get(loader, interfaces);
}
}