關於java的一個典型的動態代理

今天看書的一個過程當中,看到一個動態代理看下代碼java

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

public class DynamicProxy {
	
	
	public static void testDynamicProxy(){
		Calculator calculator = new CalculatorImpl();
		LogHandler lh = new LogHandler(calculator);
		Calculator proxy = (Calculator)Proxy.newProxyInstance(calculator.getClass().getClassLoader(), calculator.getClass().getInterfaces(), lh); //注意這裏的調用方式
		proxy.add(1, 1);
	}
	
	public static void main(String[] args){
		testDynamicProxy();
	}
	
}


interface Calculator{
	int add(int a,int b);
}

class CalculatorImpl implements Calculator{
	public int add(int a,int b){
		return a+b;
	}
}

class LogHandler implements InvocationHandler {

	Object o;
	
	LogHandler(Object o){
		this.o = o;
	}
	
	public Object invoke(Object proxy, Method method, Object[] args)  //這裏使用了反射的機制,具體這裏的method要看上面的proxy具體調用的方法
			throws Throwable {
		this.doBefore();
		Object o = method.invoke(proxy, args);
		this.doAfter();
		return o;
	}
	
	public void doBefore(){
		System.out.println("do this before");
	}
	
	public void doAfter(){
		System.out.println("do this after");
	}
	
}

這裏的好處是,可以在位置類的做用下調用須要使用類型,好處是隻須要一個類能夠處理多類型this

相關文章
相關標籤/搜索