使用Spring Introducation 让Java类实现动态语言特性

当我们没有一个实现类源代码以致不能为实现类增加新的方法时,我们在java语言中往往是无法实现的,但动态语言比(如JS),对动态对象增加可操作的方法是很容易得,我们借助Spring的Introduction这个特殊的advise,同样可以实现动态语言的这个特性

原始的业务接口及实现

packageIntroduction;

publicinterfaceISome...{

publicvoiddoSome();

}

packageIntroduction;

publicclassSomeimplementsISome...{

publicvoiddoSome()...{

System.out.println("原来的方法");

}

}

我们新增的业务接口和实现,其中实现类同时实现了业务接口和SpringIntroduction接口

packageIntroduction;

publicinterfaceIOther...{

publicvoiddoOther();

}

packageIntroduction;

importorg.aopalliance.intercept.MethodInvocation;

importorg.springframework.aop.IntroductionInterceptor;

publicclassOtherimplementsIOther,IntroductionInterceptor...{

publicvoiddoOther()...{

System.out.println("增加的职责");

}

publicObjectinvoke(MethodInvocationmethodInvocation)throwsThrowable...{

if(implementsInterface(methodInvocation.getMethod().getDeclaringClass()))...{

returnmethodInvocation.getMethod().invoke(this,methodInvocation.getArguments());

}else...{

returnmethodInvocation.proceed();

}

}

//判断是否来自与IOther接口的方法调用

publicbooleanimplementsInterface(Classclazz)...{

returnclazz.isAssignableFrom(IOther.class);

}

}

配置文件:

<?xmlversion="1.0"encoding="UTF-8"?>

<beans

xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

<beanid="some"class="Introduction.Some"/>

<beanid="other"class="Introduction.Other"/>

<beanid="otherAdvisor"class="org.springframework.aop.support.DefaultIntroductionAdvisor">

<constructor-argref="other"></constructor-arg>

<constructor-argvalue="Introduction.IOther"></constructor-arg>

[img]http://b19.photo.store.qq.com/http_imgload.cgi?/rurl4_b=b319ad0568b952709699cf254a19161bed53f2f2894a

相关推荐