JDK动态代理实现:
接口:
public interface LetRoom {
public void zf();
}
实现类:
public class FD1 implements LetRoom {
@Override
public void zf() {
System.out.println("北京公寓");
}
}
代理类:
public class MyInvction implements InvocationHandler {
LetRoom lr;
public void setLr(LetRoom lr) {
this.lr = lr;
}
//动态产生代理对象
public Object getProxy(){
/**
*
*参数一:任意给定 只要是ClassLoader类型即可
*
*参数二:统一实现的接口
*
*参数三:InvocationHandler类型数据
*
* */
return Proxy.newProxyInstance(MyInvction.class.getClassLoader(),new Class[]{LetRoom.class},this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
/**
*
* proxy:代理对象
*
* method:调用方法
*
* args:参数 null
*
*
* */
System.out.println("----房屋介绍费500----");
//使用反射调用方法
Object invoke = method.invoke(lr, args);
System.out.println("----房屋卫生费500----");
return invoke;
}
}
测试类:
public class Test {
public static void main(String[] args) {
MyInvction my1 =new MyInvction();
//设置被代理对象
my1.setLr(new FD1());
//动态产生代理对象
LetRoom proxy = (LetRoom) my1.getProxy();
proxy.zf();
}
}