基于接口的 InvocationHandler 动态代理(换种写法)

时间:2022-01-06 08:15:13

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