Java动态代理
java在java.lang.reflect包中有自己的代理支持,利用这个包可以在运行时动态的创建一个代理类
由于这个类是在运行时动态创建的,因而被称为动态代理
使用动态代理实现一个保护代理:
主人可以进入屋子,可以在外部参观屋子,陌生人只可远观,不能进入
public interface House { public void getIn(); public void visit(); }
public class RealHouse implements House { public void getIn() { System.out.println("I'm master and I can get in!"); } public void visit() { System.out.println("I'm a stranger and I could visit!"); } }
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class MasterInvocationHandler implements InvocationHandler { private House house; public MasterInvocationHandler(House house){ this.house = house; } //As a master,both get in and visit will be fine. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if(method.getName().equals("getIn")){ return method.invoke(house, args); }else{ System.out.println("Can not use this method:"+method.getName()); return null; } } }
public class StrangerInvocationHandler implements InvocationHandler { private House house; public StrangerInvocationHandler(House house){ this.house = house; } //As a stranger,only visit method was permitted. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if(method.getName().equals("visit")){ return method.invoke(house, args); }else{ System.out.println("Can not use this method:"+method.getName()); return null; } } }
import java.lang.reflect.Proxy; public class Test { public static void main(String[] args) { House h = new RealHouse(); House mh = getHouseProxy(h, "master"); House sh = getHouseProxy(h, "stranger"); mh.getIn(); mh.visit(); sh.visit(); sh.getIn(); } public static House getHouseProxy(House house,String str){ if(str.equals("master")){ return (House)Proxy.newProxyInstance(house.getClass().getClassLoader(), house.getClass().getInterfaces(), new MasterInvocationHandler(house)); }else{ return (House)Proxy.newProxyInstance(house.getClass().getClassLoader(), house.getClass().getInterfaces(), new StrangerInvocationHandler(house)); } } }
运行结果:
I'm master and I can get in! Can not use this method:visit I'm a stranger and I could visit! Can not use this method:getIn
通过上面的例子,可以看到,代码中没有显式创建代理类,代理类是在运行时通过反射由jvm自己创建的