博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
深入理解 动态代理+反射
阅读量:4109 次
发布时间:2019-05-25

本文共 1297 字,大约阅读时间需要 4 分钟。

上动态代理的代码

首先接口类

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

public class Tank implements Moveable {	public void move() {		// TODO Auto-generated method stub		System.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效果。

转载地址:http://wgvsi.baihongyu.com/

你可能感兴趣的文章
Step By Step(C调用Lua)
查看>>
Step By Step(Lua-C API简介)
查看>>
Step By Step(Lua系统库)
查看>>
Step By Step(Lua输入输出库)
查看>>
Step By Step(Lua字符串库)
查看>>
Step By Step(Lua弱引用table)
查看>>
Step By Step(Lua面向对象)
查看>>
Step By Step(Lua模块与包)
查看>>
Step By Step(Lua环境)
查看>>
Step By Step(Lua元表与元方法)
查看>>
Step By Step(Lua数据持久化)
查看>>
Step By Step(Lua数据结构)
查看>>
Step By Step(Lua编译执行与错误)
查看>>
Step By Step(Lua迭代器和泛型for)
查看>>
Step By Step(Lua函数)
查看>>
Step By Step(Lua表达式和语句)
查看>>
Step By Step(Lua基础知识)
查看>>
Step By Step(Lua开篇)
查看>>
Step By Step(编写C函数的技巧)
查看>>
Step By Step(userdata)
查看>>