您的位置:首页 > 编程语言 > ASP

AspectJ获取Annotation自定义注解的方法内容

2016-01-22 15:39 706 查看
自定义注解为:

@Target(ElementType.METHOD)

@Retention(RetentionPolicy.RUNTIME)

public @interface Tag {

public String tag();

}

需要自定义注解处理的Spring Bean对象:

@Service("fService")

public class FruitService implements IFruitService{

@Tag(tag="甜甜的")
public void eat(String fruitName){
System.out.println("======吃的水果是:"+fruitName);
}

}

现需要通过AspectJ对自定义注解进行处理,获取自定义注解Tag的方法tag()的内容:

String tag = (String)this.quietGetFromAnnotation("tag", annotation);

获取方法如下:

    private Object quietGetFromAnnotation(String methodName, Annotation annotation) {

        if (annotation == null) {

            return null;

        }

        try {

//            return annotation.annotationType().getDeclaredMethod(methodName).invoke(annotation);

        Class<?> clazz = annotation.annotationType();

        Method m = clazz.getDeclaredMethod(methodName);

        return m.invoke(annotation);

        } catch (Exception e) {

           e.printStackTrace();

        }

        return null;

    }

成功获取tag()的内容为: “甜甜的”
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: