import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//实现处理器方法(俩步:1.实现InvocationHandler接口;2.通过Proxy方法创建实例)
public class ProxyInvocationHandle implements InvocationHandler {
private Object obj;
public void setObj(Object obj) {
this.obj = obj;
}
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),obj.getClass().getInterfaces(),this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object invoke = method.invoke(obj, args);
return invoke;
}
}
通过代理对象调用方法
public class test {
public static void main(String[] args) {
ProxyInvocationHandle proxyInvocationHandle = new ProxyInvocationHandle();
proxyInvocationHandle.setObj(new houseMaster());
rent o = (rent) proxyInvocationHandle.getProxy();//
o.seeHouse();
}
}
其中rent是接口,houseMaster是它的实现类
public interface rent {
void seeHouse();
}
public class houseMaster implements rent{
@Override
public void seeHouse() {
System.out.println("房东带你看房子");
}
}
注意:代理出来的类,强转后的类型只能是接口类型,因为 jdk proxy 是在接口的基础上实现的,并且派生的代理类会继承 Proxy,即派生类的签名为 class YourClass extends Proxy implements YourInterfaceA {…}