`
mzh_2008beijing
  • 浏览: 230646 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论
收藏列表
标题 标签 来源
Java动态代理实例 动态代理
/**
 *接口类
 */
package com.mzh.common;

public interface IHelloWorld {
	public void sayHello();
}

/**
 * 实现类
 */
package com.mzh.common;

public class HelloWorldImpl implements IHelloWorld {
	public void sayHello() {
		System.out.println("Hello,World!");
	}
}

/**
 * 代理类
 */
package com.mzh.common;

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

public class HelloWorldProxy implements InvocationHandler {
	private IHelloWorld helloWorld;
	public HelloWorldProxy(IHelloWorld helloWorld){
		this.helloWorld=helloWorld;
	}
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		System.out.println("我来代理。");
		return method.invoke(this.helloWorld, args);
	}
	public static Object getInstence(IHelloWorld target){
		Class targetClass = target.getClass();
		ClassLoader loader = targetClass.getClassLoader();
		Class[] inters = targetClass.getInterfaces();
		HelloWorldProxy handler = new HelloWorldProxy(target);
		return Proxy.newProxyInstance(loader,inters, handler);
	}
}


/*
 * 测试类
 */
package com.mzh.common;

public class TestProxy {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		IHelloWorld helloWorld = new HelloWorldImpl();
		IHelloWorld helloProxy = (IHelloWorld)HelloWorldProxy.getInstence(helloWorld);
		helloProxy.sayHello();
	}
}
Global site tag (gtag.js) - Google Analytics