关于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");
	}
	
}

这里的好处是,能够在位置类的作用下调用需要使用类型,好处是只需要一个类可以处理多类型

你可能感兴趣的:(关于java的一个典型的动态代理)