Java注解是在版本5.0发布的,如今Java版本已经迭代到了13.0。我刚学习Java的时候,8.0刚刚在国内兴起。两三年过去了,Java 8.0成了大部分公司主要使用的版本。那么,今天我们来介绍Java8.0注解的一些新特性。
-
如果使用8.0之前的版本对自定义注解实现重复注解的特性,我们必须从新定义一个注解,再把需要重复使用的注解定义为数组类型的成员变量。我们来演示8.0版本之前的使用方式。
-
自定义注解:
import java.lang.annotation.*;
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD})
public @interface MyAnnotation {
String [] values();
int number();
}
- 自定义注解,并声明一个以第一个注解为类型的数组成员变量:
public @interface RepeatableAnnotation {
MyAnnotation [] value();
}
- 测试用例:
@RepeatableAnnotation({
@MyAnnotation(values = {"value1", "value2"}, number = 10),
@MyAnnotation(values = {"value1", "value2"}, number = 10)
})
public class Person {
}
-
在Java 8.0,JDK为我们提供了@Repeatable注解来使单独使用注解成可能。
-
使用@Repeatable元注解,注解到MyAnnotation上,value为我们自定义的第二个注解的运行时类(Class类对象):
@Repeatable(RepeatableAnnotation.class)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD})
public @interface MyAnnotation {
String [] values();
int number();
}
这里也表明了注解也是类。
- 使我们自定义的第二个注解与第一个注解在保留策略、作用对象和可继承性上保持一致:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD})
public @interface RepeatableAnnotation {
MyAnnotation [] value();
}
- 测试用例:
@MyAnnotation(values = {"value1", "value2"}, number = 10)
@MyAnnotation(values = {"value1", "value2"}, number = 10)
public class Person {
}
- 除了@Repeatable注解,Java 8.0还添加了两个注解作用对象:
/**
* Type parameter declaration
*
* @since 1.8
*/
TYPE_PARAMETER,
/**
* Use of a type
*
* @since 1.8
*/
TYPE_USE
- TYPE_PARAMETER表示可以作用于参数声明。我们可以为@Target注解添加这个值再去,在泛型前使用该注解:
public class Person <@MyAnnotation(values = {"value1", "value2"}, number = 10) T>{
}
- TYPE_USE表示可以作用于类型。如果为@Target设置了该值,我们可以把注解使用到一些类型上。
public void show(@MyAnnotation(values = {"value1", "value2"}, number = 10) String info)throws @MyAnnotation(values = {"value1", "value2"}, number = 10) Exception{
List<@MyAnnotation(values = {"value1", "value2"}, number = 10)String> list = new ArrayList<>();
int number = (@MyAnnotation(values = {"value1", "value2"}, number = 10) int) 10.0;
}