深入理解 动态代理+反射

来源:互联网 发布:股票提醒软件 换手率 编辑:程序博客网 时间:2024/06/05 15:15


上动态代理的代码

首先接口类

public interface Moveable {void move();}
实现类

public class Tank implements Moveable {public void move() {// TODO Auto-generated method stubSystem.out.println("Tank begin Moving...");System.out.println("Tank end Moving...");}}
代理类

public class DomProxy implements InvocationHandler {public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {Moveable t = new Tank();return method.invoke(t, args);}}
动态代理代码

InvocationHandler h = new DomProxy();Moveable t=(Moveable)Proxy.newProxyInstance(Moveable.class.getClassLoader(), Tank.class.getInterfaces(), h);t.move();
接下来我们把代理类修改下加入反射

public class NewProxy implements InvocationHandler {private String serviceName;public NewProxy(String service){this.serviceName=service;}public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {Class classType = Class.forName(serviceName);          Object obj = classType.newInstance();          return method.invoke(obj, args);}}
此时可以看到代理类中并没有实际类的代码了,而是根据传入的类名通过反射生成实例来实现的。

此时的动态代理代码如下:

InvocationHandler h1 = new NewProxy(Tank.class.getName());Moveable t1=(Moveable)Proxy.newProxyInstance(Moveable.class.getClassLoader(), Tank.class.getInterfaces(), h);t1.move();


如果把类名都存入一个Map中,那么通过不同类名生成不同的对象达到通用的效果了,类似的Spring效果。






原创粉丝点击