Java實現動態代理
阿新 • • 發佈:2022-04-19
1、實現InvocationHandler介面
這種方式只能針對介面實現類的例項物件。
interface Hello{ public void sayHello(); } class HelloImpl implements Hello{ public void sayHello(){ System.out.println("Hello"); } } public class Main { public static void main(String[] args) { Hello hello = (Hello) Proxy.newProxyInstance( HelloImpl.class.getClassLoader(), HelloImpl.class.getInterfaces(), new ProxyInvocationHandler(new HelloImpl())); hello.sayHello(); } } public class ProxyInvocationHandler implements InvocationHandler{ private Object obj; public ProxyInvocationHandler(Object obj){ this.obj = obj; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("before"); Object result=method.invoke(obj,args); System.out.println("after"); return result; } }
表面上操作的物件是介面的物件,但實際在ProxyInvocationHandler中,操作得是Hello介面的實現類的物件。
2、CGLIb
需要手動新增依賴,但實現動態代理不侷限於介面。