jdk动态代理实现:
jdk的动态代理包含两个类:Proxy、InvocationHandler.
其中InvocationHandler是一个接口,可以实现该接口通过反射的机制来进行业务的代理。
而Proxy利用InvocationHandler动态的创建一个符合某一接口的实例,生成目标类的代理对象。
package com.jxufe.proxy;
/**
* 这是一个接口类
* @author jack
* @version 创建时间:2016年5月6日 上午10:37:32
*
*/
public interface FlyAble {
public void fly();
}
package com.jxufe.proxy;
/**
* 委托类
* @author jack
* @version 创建时间:2016年5月6日 上午10:39:08
*
*/
public class AirPlane implements FlyAble {
public void fly() {
System.out.println("飞机飞行中。。。。。。。。。。");
}
}
package com.jxufe.JDkproxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import com.jxufe.proxy.AirPlane;
/**
* 这是一个代理类,代理行程
* @author jack
* @version 创建时间:2016年5月6日 上午11:08:40
*
*/
public class RouteHander implements InvocationHandler {
private AirPlane airPlane;
public RouteHander(AirPlane airPlane) {
super();
this.airPlane = airPlane;
}
public AirPlane getAirPlane() {
return airPlane;
}
public void setAirPlane(AirPlane airPlane) {
this.airPlane = airPlane;
}
/**
* proxy 被代理的对象
* method 被代理的对象的方法
* args 被代理的对象的方法的参数
*/
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("开始起飞记录行程。");
method.invoke(airPlane, args);
System.out.println("飞机降落共行驶1000km");
return null;
}
}
package com.jxufe.JDkproxy;
import java.lang.reflect.Proxy;
import com.jxufe.proxy.AirPlane;
import com.jxufe.proxy.FlyAble;
public class RoiteHanderTest {
public static void main(String[] args) {
AirPlane airPlane = new AirPlane();
RouteHander routerHander = new RouteHander(airPlane);
Class<?> cla = airPlane.getClass();
FlyAble aircraft = (FlyAble) Proxy.newProxyInstance(cla.getClassLoader(), cla.getInterfaces(),routerHander);
aircraft.fly();
}
}
结果:
开始起飞记录行程。
飞机飞行中。。。。。。。。。。
飞机降落共行驶1000km
飞机飞行中。。。。。。。。。。
飞机降落共行驶1000km