最近看董西城老师的书,有介绍到java的反射机制,做一个笔记。
首先定义一个接口类:
public interface CalculatorProtocol {
public int add(int a,int b);
public int subtract(int a,int b);
}
然后写两个类server1和server2来实现这个接口
public class Server1 implements CalculatorProtocol{
@Override
public int add(int a, int b) {
// TODO Auto-generated method stub
return a+b;
}
@Override
public int subtract(int a, int b) {
// TODO Auto-generated method stub
return a-b;
}
}
public class Server2 implements CalculatorProtocol{
@Override
public int add(int a, int b) {
// TODO Auto-generated method stub
return a+b+2;
}
@Override
public int subtract(int a, int b) {
// TODO Auto-generated method stub
return a-b-2;
}
}
然后要自己实现java.lang.reflect.InvocationHandler接口,并在invoke方法中实现对委托类的代理访问。
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
//步骤1:通过实现InvocationHandler接口创建自己的调用处理器
public class CalculatorHandler implements InvocationHandler{
//InvocationHandler类,定义了 一个invoke方法,用于处理在动态代理类对象上的方法调用。
//通常开发人员需要实现该接口,并在invoke方法中实现对委托类的代理访问。
private Object objOriginal;
public CalculatorHandler(Object obj){
this.objOriginal=obj;
}
//invoke方法:负责处理动态代理类上的所有方法调用。包含三个参数,分别代表
//@Object 代理类实例
//@method 被调用的方法对象
//@args 调用参数
//调用处理器根据这三个参数进行预处理或分派到委托类实例上执行。
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO Auto-generated method stub
Object result = method.invoke(this.objOriginal, args);
return result;
}
}
调用测试:
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
public class DynamicProxyExample {
public static void main(String args[]) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
CalculatorProtocol server = new Server1();
//1.创建自己的类调用处理器
InvocationHandler handler= new CalculatorHandler(server);
//Proxy.newProxyInstance方法封装了以下步骤:
/*
//1.通过为Proxy类制定ClassLoader对象和一组interface创建动态代理类
Class clazz=Proxy.getProxyClass(server.getClass().getClassLoader(), server.getClass().getInterfaces());
//2.通过反射机制获取动态代理类的构造函数,其参数类型是调用处理器接口类型
Constructor constructor = clazz.getConstructor(new Class[]{InvocationHandler.class});
//3.通过构造函数创建代理类实例
CalculatorProtocol proxy = (CalculatorProtocol)constructor.newInstance(new Object[]{handler});
*/
CalculatorProtocol proxy1 = (CalculatorProtocol)Proxy.newProxyInstance
(server.getClass().getClassLoader(),
server.getClass().getInterfaces(),
handler);
int r=proxy1.add(5, 3);
System.out.println("5+3="+r);
r=proxy1.subtract(10, 2);
System.out.println("10-2="+r);
}
}