前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >获取注解信息

获取注解信息

作者头像
何白白
发布2019-06-28 16:30:56
1.6K0
发布2019-06-28 16:30:56
举报

获取注解信息

新建一个注解

代码语言:javascript
复制
import java.lang.annotation.*;

@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD,ElementType.FIELD})
public @interface MyAnnotation {
    String value() default "hejiaxuan";
}

新建一个class

代码语言:javascript
复制
@MyAnnotation
public class OneClass {

    @MyAnnotation
    public String name;

}

获取class上的注解

代码语言:javascript
复制
//获取类上的所有的注解
Annotation[] annotations = OneClass.class.getAnnotations();
//根据类型获取注解
MyAnnotation annotation = OneClass.class.getAnnotation(MyAnnotation.class);
//获取本类的注解(忽略继承)
Annotation[] annotations = TwoClass.class.getDeclaredAnnotations();

获取属性上的注解

代码语言:javascript
复制
//根据类型获取属性上的注解
Field name = OneClass.class.getField("name");
MyAnnotation annotation = name.getAnnotation(MyAnnotation.class);
//获取属性上的所有注解
Annotation[] annotations = name.getAnnotations();

其他的获取注解的方法类似

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 获取注解信息
    • 新建一个注解
      • 新建一个class
        • 获取class上的注解
          • 获取属性上的注解
            • 其他的获取注解的方法类似
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档