步骤
1 定义接口
2 定义被代理的类
3 定义代理类
4 测试功能
核心代码
- 定义接口
/**
* @Classname CommonInterface
* @Description TODO
* @Date 2022-12-07 23:04
* @Created by lihw
*/
public interface CommonInterface {
void eat();
}
- 定义被代理的实现类
/**
* @Classname TestProxy
* @Description TODO
* @Date 2022-12-07 23:03
* @Created by lihw
*/
public class TestProxy implements CommonInterface{
@Override
public void eat() {
System.out.println("eating");
}
public static void main(String[] args) {
CommonInterface proxy = (CommonInterface)new ProxyDemo(new TestProxy()).getProxy();
proxy.eat();
}
}
- 定义代理类
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @Classname ProxyDemo
* @Description TODO
* @Date 2022-12-07 22:56
* @Created by lihw
*/
public class ProxyDemo implements InvocationHandler {
private Object target;
public ProxyDemo(Object target){
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("method before -------");
Object result = method.invoke(target, args);
System.out.println("method after -------");
return result;
}
public <T> T getProxy() {
return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
}
}
- 测试功能
public static void main(String[] args) {
CommonInterface proxy = (CommonInterface)new ProxyDemo(new TestProxy()).getProxy();
proxy.eat();
}
结果展示
method before -------
eating
method after -------