Java的自定义注解使用
注解目前非常的流行,很多主流框架都支持注解,而且自己编写代码的时候也会尽量的去用注解,一时方便,而是代码更加简洁。
注解的语法比较简单,除了@符号的使用之外,它基本与Java固有语法一致。Java SE5内置了三种标准注解:
@Override,表示当前的方法定义将覆盖超类中的方法。
@Deprecated,使用了注解为它的元素编译器将发出警告,因为注解@Deprecated是不赞成使用的代码,被弃用的代码。
@SuppressWarnings,关闭不当编译器警告信息。
上面这三个注解多少我们都会在写代码的时候遇到。Java还提供了4种注解,专门负责新注解的创建。
@Target
表示该注解可以用于什么地方,可能的ElementType参数有:
CONSTRUCTOR:构造器的声明
FIELD:域声明(包括enum实例)
LOCAL_VARIABLE:局部变量声明
METHOD:方法声明
PACKAGE:包声明
PARAMETER:参数声明
TYPE:类、接口(包括注解类型)或enum声明
@Retention
表示需要在什么级别保存该注解信息。可选的RetentionPolicy参数包括:
SOURCE:注解将被编译器丢弃
CLASS:注解在class文件中可用,但会被VM丢弃
RUNTIME:VM将在运行期间保留注解,因此可以通过反射机制读取注解的信息。
@Document
将注解包含在Javadoc中
@Inherited
允许子类继承父类中的注解
定义一个自定义注解的方式
/**
* 测试自定义注解
* @author gjw
* @createTime 2019/5/21 15:56
*/
@Target(ElementType.TYPE) //设定注解标注的位置
@Retention(RetentionPolicy.RUNTIME) //需要寿命级别保存注解信息
@Deprecated //该注解包含在Javadoc中
@Inherited //允许子类继承该注解
public @interface TestAnnotation {
}
注解的可用的类型包括以下几种:所有基本类型、String、Class、enum、Annotation、以上类型的数组形式。元素不能有不确定的值,即要么有默认值,要么在使用注解的时候提供元素的值。而且元素不能使用null作为默认值。注解在只有一个元素且该元素的名称是value的情况下,在使用注解的时候可以省略“value=”,直接写需要的值即可。
下面看一个定义了元素的注解。
/**
* @author gjw
* @createTime 2019/5/21 16:02
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
int id();
String description()default "no description";
}
使用注解
/**
* @author gjw
* @createTime 2019/5/21 16:05
*/
public class PasswordUtils {
@MyAnnotation(id = 47, description = "Passwords must contain at least one numeric")
public boolean validatePassword(String password) {
return (password.matches("\\w*\\d\\w*"));
}
@MyAnnotation(id = 48)
public String encryptPassword(String password) {
return new StringBuilder(password).reverse().toString();
}
public static void main(String[] args) {
List<Integer> usrCases = new ArrayList<Integer>();
Collections.addAll(usrCases,45,46,47,48);
trackUseCases(usrCases,PasswordUtils.class);
}
public static void trackUseCases(List<Integer> usrCases, Class<?> clazz) {
for (Method method:clazz.getMethods()){
MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class); //使用反射获得注解的属性
if (myAnnotation != null){
System.out.println("Found MyAnnotation:" + myAnnotation.id() + " " + myAnnotation.description());
usrCases.remove(new Integer(myAnnotation.id()));
}
}
for (int i:usrCases){
System.out.println("Warning:Missing usr case-" + i);
}
}
}
结果
Found MyAnnotation:47 Passwords must contain at least one numeric
Found MyAnnotation:48 no description
Warning:Missing usr case-45
Warning:Missing usr case-46