`
return_space
  • 浏览: 20058 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

动态代理

 
阅读更多

动态代理:即JAVA在运行时,动态的创建代理类。

使用动态代理,实现接口与实现类可以不直接发送联系,在运行期,实现动态的关联关系。

主要使用JAVA的反射技术,使用的接口InvocationHandler,代理类Proxy

具体实现的代码如下:

package com.mkf.pattern;

public interface InterfaceOne {
	public void operation();
}

package com.mkf.pattern.impl;

import com.mkf.pattern.InterfaceOne;

public class Source implements InterfaceOne {

	@Override
	public void operation() {
		System.out.println("源被调用:" + Source.class.getName());
	}

}

package com.mkf.pattern.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class DynamicProxy implements InvocationHandler {
	private Object sourceed;

	public DynamicProxy(Object sourceed) {
		super();
		this.sourceed = sourceed;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		System.out.println("代理对象" + proxy.getClass().getName());
		Object result;

		result = method.invoke(this.sourceed, args);

		return result;
	}

}

package com.mkf;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

import com.mkf.pattern.InterfaceOne;
import com.mkf.pattern.impl.Source;
import com.mkf.pattern.proxy.DynamicProxy;

public class TestDynamicProxy {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		InterfaceOne io = new Source();
		
		InvocationHandler iHandler = new DynamicProxy(io);
		
		//获得代理对象
		Class<?> clazz = Proxy.getProxyClass(io.getClass().getClassLoader(), 
				io.getClass().getInterfaces());

			try {
				Constructor<?> c = clazz.getConstructor(
						new Class[]{InvocationHandler.class});
				InterfaceOne ioOne = (InterfaceOne)c.newInstance(new Object[]{iHandler});
				System.out.println("产生的动态代理对象 : " + ioOne.getClass().getName());
				ioOne.operation();
			} catch (Exception e) {
			}
		System.out.println("---------------------------------------------");
		Object obj = Proxy.newProxyInstance(io.getClass().getClassLoader(), 
				io.getClass().getInterfaces(), 
				iHandler);
		
		System.out.println("获得源对象:  " + obj);
		InterfaceOne ioOne = (InterfaceOne)obj;
		System.out.println("---------------------------------------------");
		ioOne.operation();
		
		System.out.println("---------------------------------------------");
		iHandler = Proxy.getInvocationHandler(obj);
		System.out.println(iHandler.getClass().getName());
		System.out.println(iHandler);
	}

}

 

执行结果为:

产生的动态代理对象 : $Proxy0
代理对象$Proxy0
源被调用:com.mkf.pattern.impl.Source
---------------------------------------------
代理对象$Proxy0
获得源对象:  com.mkf.pattern.impl.Source@10d448
---------------------------------------------
代理对象$Proxy0
源被调用:com.mkf.pattern.impl.Source
---------------------------------------------
com.mkf.pattern.proxy.DynamicProxy
com.mkf.pattern.proxy.DynamicProxy@e0e1c6

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics