1. 程式人生 > >基於介面的 InvocationHandler 動態代理(換種寫法)

基於介面的 InvocationHandler 動態代理(換種寫法)

InvocationHandler is the interface implemented by the invocation handler of a proxy instance.

Each proxy instance has an associated invocation handler. When a method is invoked on a proxy instance, the method invocation is encoded and dispatched to the invoke method of its invocation handler.

 

package cn.zno.newstar.base.utils.text;

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

public class ProxyDemo {
    public static void main(String[] args) {
        Target target = new TargetImpl();
        TargetIH ih = new TargetIH();
        Target proxy 
= ih.newProxyInstance(target); proxy.doSomething(); proxy.doSomethingElse(); } } interface Target { void doSomething(); void doSomethingElse(); } class TargetImpl implements Target { @Override public void doSomething() { System.out.println("TargetImpl doSomething"); } @Override
public void doSomethingElse() { System.out.println("TargetImpl doSomethingElse"); } } class TargetIH implements InvocationHandler { private Object target; @SuppressWarnings("unchecked") public <T> T newProxyInstance(T target) { this.target = target; Class<?> clazz = target.getClass(); // a proxy instance 的 invocation handler 實現 InvocationHandler 介面 return (T) Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this); } @Override public Object invoke(Object proxy, Method method, Object[] args) { System.out.println("proxy start"); Object result = null; /* * 這裡可以正則方法名,判斷引數,判斷註解;不同場景動態代理不同的事 * * */ try { result = method.invoke(target, args); } catch (Exception e) { // do something } System.out.println("proxy end"); return result; } }

 

結果:

proxy start
TargetImpl doSomething
proxy end
proxy start
TargetImpl doSomethingElse
proxy end