Java动态代理链_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Java动态代理链

Java动态代理链

 2013/10/30 0:58:02  zhangyan19870108  程序员俱乐部  我要评论(0)
  • 摘要:需要被代理的接口和类。注意:必须要定义接口。packagecom.yan.proxy.object;publicinterfaceProxyObjectI{publicvoidsayHello();}被代理的类packagecom.yan.proxy.object;publicclassProxyedObjectimplementsProxyObjectI{@OverridepublicvoidsayHello(){System.out.println("hello");}
  • 标签:Java 代理
需要被代理的接口和类。注意:必须要定义接口。
class="java" name="code">package com.yan.proxy.object;

public interface ProxyObjectI {
	public void sayHello();
}
被代理的类
package com.yan.proxy.object;

public class ProxyedObject implements ProxyObjectI{
	@Override
	public void sayHello() {
		System.out.println("hello");
	}
	
}
两个代理类authority log
package com.yan.proxy.object;

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

public class AuthorityProxy implements InvocationHandler {

	private Object proxy;
	
	
	@Override
	public Object invoke(Object obj, Method method, Object[] args)
			throws Throwable {
		
		doBefore();
		Object result =  method.invoke(proxy, args);
		doAfter();
		return result;
	}
	
	public AuthorityProxy(Object proxy) {
		this.proxy = proxy;
	}

	private void doBefore() {
		System.out.println("before you are authoried! ");
	}
	
	private void doAfter() {
		System.out.println("after you are authoried! ");
	}

}


package com.yan.proxy.object;

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

public class LogProxy implements InvocationHandler {

	private Object proxy;
	
	
	public LogProxy(Object proxy) {
		this.proxy = proxy;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		doBefore();
		Object result = method.invoke(this.proxy, args);
		doAfter();
		return result;
	}
	
	private void doBefore() {
		System.out.println("before logging.............. ");
	}
	
	private void doAfter() {
		System.out.println("after logging..............");
	}

}

测试类
package com.yan.proxy.object;

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

public class Test {

	public static void main(String[] args) throws InstantiationException, IllegalAccessException {
		
		ProxyObjectI object = new ProxyedObject();
		InvocationHandler authHandler = new AuthorityProxy(object);
		ProxyObjectI authProxy = (ProxyObjectI) Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), authHandler);
		InvocationHandler logHandler = new LogProxy(authProxy);
		ProxyObjectI proxy = (ProxyObjectI) Proxy.newProxyInstance(authProxy.getClass().getClassLoader(), authProxy.getClass().getInterfaces(), logHandler);
		proxy.sayHello();
		
	}
}

输出结果:

before logging..............
before you are authoried!
hello
after you are authoried!
after logging..............
可以看到对象被一层一层的代理对象所封装。
  • TestDynamicProxy.tar.gz (3.1 KB)
  • 下载次数: 0
上一篇: Java版Mysql4.1之前的old_password加密算法。 下一篇: 没有下一篇了!
发表评论
用户名: 匿名