读书人

java基础-反照与动态代理

发布时间: 2013-08-06 16:47:25 作者: rapoo

java基础-反射与动态代理

public class Proxy??
Proxy 提供用于创建动态代理类和实例的静态方法,它还是由这些方法创建的所有动态代理类的超类。


public interface InvocationHandler
InvocationHandler 是代理实例的调用处理程序 实现的接口。
看下面一个典型的应用

public interface SimpleService {
??? public int getNumber();
}


public class SimpleServiceImpl implements SimpleService {
??? @Override
??? public int getNumber() {
??? ??? return 1;
??? }
}


public class SimpleInvocationHandler implements InvocationHandler {
??? private SimpleService simpleService;
??? SimpleInvocationHandler(SimpleService simpleService){
??? ??? this.simpleService = simpleService;
??? }
???
??? @Override
??? public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {
??? ??? //? Object proxy 这个对象比较有意思,打印出来会出现堆栈溢出

??????? if(method.getName().equals("getNumber")){
??? ??? ??? System.out.println("方法调用之前");
??? ??? ??? return method.invoke(simpleService, args);
??? ??? }
??? ??? return null;
??? }
}

public class Test {
??? public static void main(String[] args) throws InstantiationException, IllegalAccessException {
??? ??? SimpleService simpleService = new SimpleServiceImpl();
??? ??? InvocationHandler h???????? = new SimpleInvocationHandler(simpleService);
??? ??? SimpleService proxy???????? = (SimpleService)????????????????????????????????????? Proxy.newProxyInstance(SimpleService.class.getClassLoader(),new Class[] {SimpleService.class }, h);
??? ??? proxy.getNumber();
??? }
}
其中比较有趣的是,SimpleService proxy = (SimpleService) Proxy.newProxyInstance(SimpleService.class.getClassLoader(), new Class[] {? SimpleService.class }, h);在调试的过程中,在ide中竟然看不到proxy对象的数据结构,我们可以作一个对比,经过代理包装过的类实例和我们生成的类实例,数据结构完全不同。

jdk的Proxy.java核心代码如下
Class cl = getProxyClass(loader, interfaces);
Constructor cons = cl.getConstructor(constructorParams);
return (Object) cons.newInstance(new Object[] { h });
其中new Object[] { h }中的h即传入的SimpleInvocationHandler。

读书人网 >编程

热点推荐