注解学习

自定义注解

方法参数的注解

@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD, ElementType.PARAMETER})
public @interface Parama {
    String value() default "";

    String name() default "";

}

方法的注解

@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = {ElementType.TYPE, ElementType.METHOD})
public @interface MyAnnotation {
    String color() default "white";
}

注解获取解析


@MyAnnotation(color = "yellow")
public class Main {

    public static void main(String[] args) {
        System.out.println("Hello World!");
        if (Main.class.isAnnotationPresent(MyAnnotation.class)) {
            System.out.println("获取到runtime @ ");
        }
        Annotation[] subs = Main.class.getAnnotations();

        MyAnnotation myAnnotation = Main.class.getAnnotation(MyAnnotation.class);
        if (myAnnotation != null) {
            System.out.println(myAnnotation + " : " + myAnnotation.color());

        }
        Main main = new Main();
       main.sayHello("132","XXXX");
    }
@Parama(name = "name",value = "xxx")
    public  void sayHello(@Parama("hello") String msg, @Parama("xx") String xx) {

    for (Method method : this.getClass().getMethods()) {

        if(method.getAnnotation(Parama.class) == null ){
            continue;
        }
        Annotation[][] params = method.getParameterAnnotations();

        for (int i = 0; i < params.length; i++) {
            Annotation[] annotations = params[I];
            for (int j = 0; j < annotations.length; j++) {
                Annotation annotation = annotations[j];
                if (annotation instanceof Parama) {
                    Parama parama = (Parama) annotation;
                    String pValue = parama.value();
                    String pName = parama.name();

                    System.out.println("获取到funcation的参数注解:" + "值:"+ pValue +" : 参数名:"+pName);
                }
            }
        }
    }
    }
}

结果

http://springforall.ufile.ucloud.com.cn/static/img/7e9fd2d95ec8f790f9dca29ffdf6c3331559212

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 什么是注解注解分类注解作用分类 元注解 Java内置注解 自定义注解自定义注解实现及使用编译时注解注解处理器注解处...
    Mr槑阅读 1,100评论 0 3
  • Java 注解 学习笔记 前言: 注解是一个很早就出现的技术,之前一直没有时间就这么拖着,现在闲暇之时学习一下,...
    真的有照片阅读 1,035评论 0 1
  • 前言 在前面我们学习过java的注解的语法,说明了注解的作用;前面举的例子是运行时注解,这样会影响我们代码执行的效...
    weiinter105阅读 1,280评论 0 0
  • 元注解: 元注解的作用就是负责注解其他注解。Java5.0定义了4个标准的meta-annotation类型,它们...
    badcyc阅读 397评论 0 1
  • 我们平常写Java代码,对其中的注解并不是很陌生,比如说写继承关系的时候经常用到@Override来修饰方法。但是...
    于晓飞93阅读 729评论 1 6