動態代理的實現

public interface IHelloWorld {

	void sayHello();
	void sayBye();
	void saySomething(String msg);
}

 實例類如下:

public class HelloWorld implements IHelloWorld {

	@Override
	public void sayHello() {
		System.out.println("Hello World");
	}

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

	@Override
	public void saySomething(String msg) {
		System.out.println("I want to say :I love you");
	}

}

 handler的實現類:

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

public class ReflectProxy implements InvocationHandler {

	private Object proxyObject;
	
	public ReflectProxy(Object proxyObject) {
		this.proxyObject = proxyObject;
	} 
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)	throws Throwable {
		doBeforeCalling(method);
		method.invoke(proxyObject, args);
		doAfterCalling(method);
		return null;
	}

	private void doBeforeCalling(Method method) {
		System.out.println("before calling [" + method.getName() + "]");
	}
	
	private void doAfterCalling(Method method) {
		System.out.println("after calling [" + method.getName() + "]");
	}
}

 測試類如下:

import java.lang.reflect.Proxy;

public class ReflectProxyText {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		HelloWorld helloworld = new HelloWorld();
		ReflectProxy handler  = new ReflectProxy(helloworld);
		IHelloWorld helloword = (IHelloWorld)Proxy.newProxyInstance(helloworld.getClass().getClassLoader(), helloworld.getClass().getInterfaces(), handler);
		helloword.sayHello();
	}
}

 Spring中的通知功能也許就是使用動態代碼實現的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章