1.Base接口
public interface Base {
void baseMethod();
}
2.CustomHandler类
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class CustomHandler<T> implements InvocationHandler {
T target;
public CustomHandler(T target){
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("start...");
Object result = method.invoke(target, args);
System.out.println("end...");
return result;
}
}
3.测试
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class ProxyTest {
public static void main(String[] args) {
Base base = () -> System.out.println("in hand...");
InvocationHandler handler = new CustomHandler<>(base);
// 生成代理对象
Base baseProxy = (Base)Proxy.newProxyInstance(ProxyTest.class.getClassLoader(), new Class[]{Base.class}, handler);
baseProxy.baseMethod();
}
}
start...
in hand...
end...
Process finished with exit code 0