实现一个JDK动态代理

it2026-04-09  5

package 代理模式; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * 描述: * 动态代理 * 本质就是两个类实现同一个接口,被代理类调用代理类的方法 前后可以做一些别的事情。 * * @author 小纸人 * @create 2019-08-04 1:44 */ interface Human { String getBelief(); void eat(String food); } //被代理类 class SuperMan implements Human { @Override public String getBelief() { System.out.println("I believe I can fly!"); return "I believe I can fly!"; } @Override public void eat(String food) { System.out.println("我喜欢吃” " + food); } } /* * 实现动态代理需要解决的问题 * 问题一: * 如何根据加载到内存中的被代理类,动态的创建一个代理类及其对象 * 问题二: * 当通过代理类的对象调用方法时,如何动态的去调用被代理类中的同名方法 * */ class ProxyFactory { //调用此方法解决问题 1 public static Object getProxyInstance(Object obj) {//obj: 被代理类的对象 MyInvocationHandler handler = new MyInvocationHandler(); handler.bind(obj); return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), handler); } } class MyInvocationHandler implements InvocationHandler { private Object obj;//需要使用被代理类的对象进行赋值 public void bind(Object obj) { this.obj = obj; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // method 即为代理类调用的方法,此方法也就作为了被代理类要调用的方法 //obj : 被代理类的对象 System.out.println("动态代理来了,他来了!!"); Object returnVal = method.invoke(obj, args); System.out.println("动态代理走了,他走了!!"); return returnVal; } } public class ProxyTest { public static void main(String[] args) { SuperMan superMan = new SuperMan(); Human proxyInstance = (Human) ProxyFactory.getProxyInstance(superMan); proxyInstance.eat("芝士汉堡"); proxyInstance.getBelief(); NikeClothFactory nikeClothFactory = new NikeClothFactory(); ClothFactory proxyInstance1 = (ClothFactory) ProxyFactory.getProxyInstance(nikeClothFactory); proxyInstance1.produceCloth(); } }

 

最新回复(0)