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

本文介绍如何使用 Spring 的 IntroductionInterceptor 和 DefaultIntroductionAdvisor 实现为已有类动态引入新接口的功能,无需修改原有类源码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

原始的业务接口及实现

package Introduction;

public interface ISome ...{
public void doSome();

}


package Introduction;

public class Some implements ISome ...{

public void doSome() ...{
System.out.println("原来的方法");
}

}


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

package Introduction;

public interface IOther ...{
public void doOther();

}


package Introduction;


import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.IntroductionInterceptor;

public class Other implements IOther, IntroductionInterceptor ...{

public void doOther() ...{
System.out.println("增加的职责");
}

public Object invoke(MethodInvocation methodInvocation) throws Throwable ...{
if(implementsInterface(methodInvocation.getMethod().getDeclaringClass()))...{
return methodInvocation.getMethod().invoke(this, methodInvocation.getArguments());
}else...{
return methodInvocation.proceed();
}

}
//判断是否来自与IOther接口的方法调用
public boolean implementsInterface(Class clazz) ...{
return clazz.isAssignableFrom(IOther.class);
}

}


配置文件:

<?xml version="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/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">


<bean id="some" class="Introduction.Some"/>
<bean id="other" class="Introduction.Other"/>

<bean id="otherAdvisor" class="org.springframework.aop.support.DefaultIntroductionAdvisor">
<constructor-arg ref="other"></constructor-arg>
<constructor-arg value="Introduction.IOther"></constructor-arg>
[img]http://b19.photo.store.qq.com/http_imgload.cgi?/rurl4_b=b319ad0568b952709699cf254a19161bed53f2f2894a
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值