jdk自带的动态代理类生成测试

设计模式的代理模式有静态代理和动态代理两种。方法是让两个类实现同一接口,并实现一个方法C。例如:类A(代理类)和类B,我们可以在类A的方法C中添加一些功能(日志等),并调用类B的方法。这样,我们可以在类B中只关注核心功能的开发,解耦合。在调用时只调用代理类的相关方法。但这样会造成代理类的过多,所以引入动态代理。

定义接口:

package proxy;

public interface StudentService {
    void study();
}

接口实现类:

package proxy;

public class StudentServiceImpl implements StudentService {

	public void study() {
		System.out.println("我是学生  谢谢");
	}

}

测试:

package proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class TestProxy {
    public static void main(String[] args) {
    	final StudentService s=new StudentServiceImpl();
    	//三个参数 类加载器 实现接口 额外功能方法
		StudentService serviceProxy=(StudentService)Proxy.newProxyInstance(TestProxy.class.getClassLoader(),new Class[]{StudentService.class}, 
        new InvocationHandler(){
            //参数 代理类 方法   方法参数
			public Object invoke(Object proxy, Method method, Object[] args)
					throws Throwable {
				System.out.println("额外功能  开始");
				method.invoke(s, args);
				System.out.println("额外功能  结束");
				return null;
			}
			
		});
		serviceProxy.study();
	}
}

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42434063/article/details/107899407