package com.su.liuqing.proxy_;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyTest {
// 目标接口
public interface TarInterface {
void say();
}
// 调用处理器
public static class MyHandler<T> implements InvocationHandler {
// 目标对象
private final T target;
public MyHandler(T target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("方法执行前");
// 目标方法执行
return method.invoke(target, args);
}
}
public static void main(String[] args) {
// 目标对象
TarInterface target = new TarInterface() {
private final String name = "tar";
public void say() {
System.out.println("hello");
}
};
MyHandler<TarInterface> myHandler = new MyHandler<>(target);
// 创建代理对象
Object proxyInstance = Proxy.newProxyInstance(ProxyTest.class.getClassLoader(), new Class[]{TarInterface.class}, myHandler);
TarInterface p = (TarInterface) proxyInstance;
p.say();
}
}
标签:Java,target,Object,class,Proxy,TarInterface,public From: https://www.cnblogs.com/sung1024/p/17578573.html