JAVA 学习笔记(二)-注解

Java注解相当于一种标记,在程序中加了注解等于为程序打上一个标记,javac编译器,开发工具或者其他程序可以用反射来了解你的类以及各种元素有没有这样的标记,有则进行相应的处理,标记可以加在 包,类,字段,方法,方法的参数以及局部变量。
注解关键字:
@interface

//简单的注解定义
public @interface MyAnnotation {

}

@Retention 元注解,表示需要在什么级别保存该注释信息(生命周期)。
RententionPolicy.SOURCE 停留在Java源文件,编译就取消。
RetentionPolicy.CLASS 停留在class文件,但会被VM丢弃。
RetentionPolicy.RUNTIME 内存中的字节码,VM将在运行时保留,因此可以通过反射机制读取注解信息。

@Target 元注解,表示该注解用于什么地方。
ElementType.CONSTRUCTOR 构造器声明
ElementType.FIELD 成员变量,对象,属性
ElementType.LOCAL_VARIBLE 局部变量声明
ElementType.METHOD 方法声明
ElementType.PACAGE 包声明
ElementType.PARAM 参数声明
ElementType.TYPE 类、接口或者enum声明

@Documented 将注解包含在JavaDoc中
@Inherited 允许子类继承
@Repeatable 重复注解 JAVA8 新特性


@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
public @interface MyAnnotation {

    String color();

    String value() default "My name is  johnson";

    int[] array() ;
}
@MyAnnotation(color="red",array={4,5,3})
public class AnnotationInsatance {

    public static void main(String[] args){
    //验证是否存在注解
        if(AnnotationInsatance.class.isAnnotationPresent(MyAnnotation.class)){
        //获取注解
            MyAnnotation annotation=AnnotationInsatance.class.getAnnotation(MyAnnotation.class);
            System.out.println(annotation);
            System.out.println(annotation.color());
            System.out.println(annotation.array());
            System.out.println(annotation.value());
        }
    }
}

Java8 新特性 重复注解,允许同一类型的注解多次使用在一个类、方法、变量等上面。
java8之前对于重复注解的也有解决办法,但是比较繁琐。

//定义注解
public @interface Authority {
     String role();
}
//定义注解  成员变量上面注解的数组
public @interface Authorities {
    Authority[] value();
}

public class RepeatAnnotationUseOldVersion {
    //变向的重复注解
    @Authorities({@Authority(role="Admin"),@Authority(role="Manager")})
    public void doSomeThing(){
    }
}

下面是java8的解决办法

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD})
@Repeatable(MyAnnotations.class)
public @interface MyAnnotation {

    String color();

    String value() default "My name is  johnson";

    int[] array() ;


}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD})
public @interface MyAnnotations {

    MyAnnotation[] value();
}

public class RepeatAnnotationUseNewVersion {
    @MyAnnotation(color="red",array={4,5,3})
    @MyAnnotation(color="red",array={4,5,3})
    public void doSomeThing(){ }
}

要使用好注解,必须熟悉java的反射机制,注解的解析都是通过反射来完成。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值