javaassist获取方法跟注解,以及获取类注解 annotations总结

测试类

package helloworldref;
import org.osoa.sca.annotations.Reference;
import org.osoa.sca.annotations.Service;


/**
 * The HelloWorld service implementation
 */


@Service(HelloWorldService.class)
public class HelloWorldServiceComponent implements HelloWorldService {
   
    HelloWorldService helloWorldService;


    public String getGreetings(String name) {
        System.out.println("Called getGreetings");
        return helloWorldService.getGreetings(name);
    }




    @Reference
    public void setHelloWorldService(HelloWorldService helloWorldService) {
        System.out.println("Injected helloWorldService");        
        this.helloWorldService = helloWorldService;
    }
}

假设我们我们已经获取到CtClass;

这里定义   CtClass claName

以此类为例,我们要通过javaassist 获取到这个类中

1.@Reference注释的方法setHelloWorldService中参数HelloWorldService 的名字以及它的包名。

这里定义  
CtClass claName =null;
CtMethod[] ms = claName.getMethods();
for (int i = 0; i < ms.length; i++) {
// 获取方法信息
MethodInfo methodInfo = ms[i].getMethodInfo();
// 获取注释信息
AnnotationsAttribute atrr = (AnnotationsAttribute) methodInfo
.getAttribute(AnnotationsAttribute.visibleTag);
if (atrr != null) {
// 参数
if (atrr.toString().equals("@org.osoa.sca.annotations.Reference")) {
if (ms[i].getName().startsWith("set")) {
//通过截取set方法获取参数名字当然这里必须是javabean形式
String msName=ms[i].getName().substring(3);
//输出:msName=helloWorldService

try {
// 获取包,当然还可以通过方式获取参数名字
if (ms[i].getParameterTypes() != null) {
String cc = ms[i].getParameterTypes()[0].getName();
//cc。就是包+类名。
}
} catch (NotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


 2.获取类上面的自定义注解
@Service(HelloWorldService.class)注释里的HelloWorldService.class

其实就是一句话

Service annotations=(Service) claName .getAnnotation(Service.class);

然后 :annotations.方法 

妈妈咪。打字好累。。睡觉。。先写到这吧




这里定义   CtClass claName
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值