动态代理模板
代理类生成(ProxyInvocationHandler)
package com.cn.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyInvocationHandler implements InvocationHandler {
private Object target;
public void setTarget(Object target){
this.target = target;
}
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
log(method.getName());
Object result = method.invoke(target, args);
return result;
}
public void log(String msg){
System.out.println("执行了"+msg+"方法");
}
}
测试类(ProxyClient)
package com.cn.proxy;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.Test;
public class ProxyClient {
@Test
public void test() {
Host host = new Host();
ProxyInvocationHandler handler = new ProxyInvocationHandler();
handler.setTarget(host);
Rent proxy = (Rent) handler.getProxy();
proxy.rent();
}
}
抽象接口(Rent)
package com.cn.proxy;
public interface Rent {
public void rent();
}
真实对象(Host)
package com.cn.proxy;
public class Host implements Rent {
public void rent() {
System.out.println("要出租房子!");
}
}