进阶day13-静态代理实现

This commit is contained in:
2026-04-11 11:01:10 +08:00
parent 2fcec5ec75
commit 8d80caa0b3
6 changed files with 148 additions and 0 deletions

View File

@@ -0,0 +1,41 @@
package com.inmind.proxy01;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/*
静态代理:直接定义一个固定的类,增强某个类的功能(JingJiRen)
动态代理:不用定义一个固定的类,动态地增强某个类的功能
需求:蔡徐坤的类不能改变,也不能定义经纪人类,但是还想对蔡徐坤的唱跳功能,增强金额判断
此时只能使用动态代理.
*/
public class Demo03 {
public static void main(String[] args) {
//创建出被代理的类-蔡徐坤
CaiXuKun caiXuKun = new CaiXuKun();
//动态代理参数一:类加载器
ClassLoader classLoader = caiXuKun.getClass().getClassLoader();
//动态代理参数二:代理对象要与被代理对象拥有相同的功能,(实现同一套接口)
Class<?>[] interfaces = caiXuKun.getClass().getInterfaces();
//动态代理参数三:处理器对象,用来处理代理对象的业务逻辑
InvocationHandler handler = new InvocationHandler() {
/*
注意动态代理对象singerProxy调用任意方法功能都会引起处理器的invoke方法来执行
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("处理器的invoke方法执行了");
return null;
}
};
//动态地创建出一个代理对象(类似一个经纪人)
Singer singerProxy = (Singer) Proxy.newProxyInstance(classLoader, interfaces, handler);//多态
singerProxy.dance(10);
singerProxy.sing(10);
}
}