JDK動態代理的一個例子


1.目標類接口

package com.arvon.jdkproxy;

/**
 * 目標類接口
 * 目標類和動態生成的代理對象都實現的接口
 *@author Huangwen
 *2017-3-29
 */
public interface ITargetClass {
	
	/**
	 * 主業務邏輯方法
	 */
	public void mainLogicMethod();
	
}


2.目標類實現類

package com.arvon.jdkproxy;

public class TargetClassImpl implements ITargetClass {

	public void mainLogicMethod() {
		System.out.println(">>>>>>>TargetClassImpl.mainLogicMethod(),主業務方法執行...");
	}
}


3.代理對象的攔截器

package com.arvon.jdkproxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
 * 代理對象的攔截器
 *@author Huangwen
 *2017-3-29
 */
public class TargetClassInterceptor implements InvocationHandler {
	private TargetClassImpl targetClassImpl;
	public TargetClassInterceptor(TargetClassImpl targetClassImpl) {
		this.targetClassImpl = targetClassImpl;
	}
	/**
	 * 生成的代理對象 所實現目標類接口中定義的相關方法的具體實現
	 */
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		System.out.println(">>>>>>before method.invoke(),這裏代表代理對象在主業務邏輯方法執行前織入的代碼");
		method.invoke(targetClassImpl, args);
		System.out.println(">>>>>>>after method.invoke(),這裏代表代理對象在主業務邏輯方法執行後織入的代碼");
		return null;
	}
}

4.測試類

package com.arvon.jdkproxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
/**
 * 客戶端 測試類
 *@author Huangwen
 *2017-3-29
 */
public class Client {
	public static void main(String[] args) {
		TargetClassImpl targetClassImpl = new TargetClassImpl();
		targetClassImpl.mainLogicMethod();
		System.out.println("====================================");
		InvocationHandler h = new TargetClassInterceptor(targetClassImpl);
		/**
		 * 以下代碼會生成一個$Proxy對象,該對象實現了ITargetClass,具體的方法體就是InvocationHandler裏面的invoke方法。
		 */
		ITargetClass proxyInstance =(ITargetClass) Proxy.newProxyInstance(targetClassImpl.getClass().getClassLoader(), targetClassImpl.getClass().getInterfaces(), h);
		proxyInstance.mainLogicMethod();
	}
}

5.打印的結果

>>>>>>>TargetClassImpl.mainLogicMethod(),主業務方法執行...
====================================
>>>>>>before method.invoke(),這裏代表代理對象在主業務邏輯方法執行前織入的代碼
>>>>>>>TargetClassImpl.mainLogicMethod(),主業務方法執行...
>>>>>>>after method.invoke(),這裏代表代理對象在主業務邏輯方法執行後織入的代碼


理解Jdk動態代理的原理是理解spring aop 原理的前提。




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