(略)
1、基于接口的动态代理,JDK官方的Proxy类,被代理的类至少实现一个接口。
2、借助第三方CGLib类,被代理的类不是被final修饰的最终类。
接口类
public interface IActor { public void basicAct(float money); public void dangerAct(float money); }
实现类
public class Actor implements IActor { public void basicAct(float money) { System.out.println("Begin basic act, get " + money); } public void dangerAct(float money) { System.out.println("Begin danger act, get " + money); } }
业务逻辑
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class Client { public static void main(String[] args) { final Actor actor = new Actor(); IActor proxyActor = (IActor) Proxy.newProxyInstance(actor.getClass().getClassLoader(), actor.getClass().getInterfaces(), new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String name = method.getName(); Float money = (Float) args[0]; Object rtValue = null; if ("basicAct".equals(name)) { if (money < 2000) { rtValue = method.invoke(actor, money/2); } } if ("dangerAct".equals(name)) { if (money >= 5000) { rtValue = method.invoke(actor, money/2); } } return rtValue; } }); proxyActor.basicAct(8000f); proxyActor.dangerAct(50000f); } }
原文:https://www.cnblogs.com/jerryleeplus/p/12080133.html