`

JAVA动态代理

 
阅读更多
Thinking in java 的一个动态代理的例子
package com.liuc.test.think.chapter14;

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

public class SimpleDynamicProxy {

	public static void consumer(Interface inte){
		inte.doSomething();
		inte.somethingElse("bonbo");
	}
	
	public static void main(String[] args) {
		RealObject realObject=new RealObject();
		consumer(new RealObject());
		System.out.println("=================");
		Interface proxy=(Interface) Proxy.newProxyInstance(Interface.class.getClassLoader(),
				new Class[]{Interface.class}, 
				new DynamicProxyHandler(realObject));
		consumer(proxy);
	}
}

class DynamicProxyHandler implements InvocationHandler{
	private Object proxied;
	public DynamicProxyHandler(Object proxied) {
		this.proxied=proxied;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		System.out.println("******proxy:"+proxy.getClass()+",method:"+method+",args:"+args);
		if (args!=null) {
			for(Object arg:args){
				System.out.println("        "+arg);
			}
		}
		return method.invoke(proxied, args);
	}
	
}


interface Interface{
	void doSomething();
	void somethingElse(String arg);
}

class RealObject implements Interface{

	@Override
	public void doSomething() {
		System.out.println("doSomething");
		
	}

	@Override
	public void somethingElse(String arg) {
		System.out.println("somethingElse:"+arg);
		
	}
	
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics