注解

  • 卫雪峰
  • 7 Minutes
  • May 18, 2019

注解

注解(元数据)为我们在代码中添加信息提供了一种形式化的方法,使我们可以在稍后某个时刻非常方便的使用这些数据。

三种标准注解:@Override, @Deprecated, @SuppressWarnings

四种元注解: @Target, @Rentetion, @Documented, @Inherited(允许子类继承父类中的注解)

1 基本语法

1.1 定义注解

1
2
3
@Target(ElementType.METHOD)
@Rentention(RententionPolicy.RUNTIME)
public @interface Test{}

案例:使用注解掌握项目进度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UseCase {
public int id();
public String desc() default "no description";
}

public class PasswordUtil {

@UseCase(id = 1, desc = "Password must contain at least one numeric")
public boolean validatePassword(String password){
return password.matches("\\w*\\d\\w*");
}

@UseCase(id = 2)
public String encryptPassword(String password){
return new StringBuffer(password).reverse().toString();
}

@UseCase(id = 3, desc = "new password can not equal previously used ones")
public boolean checkForNewPassword(List<String> prePasswords, String newPassword){
return !prePasswords.contains(newPassword);
}
}

1.2 编写注解处理器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 public static void trackUseCases(List<Integer> useCases, Class<?> clz) {
for (Method method : clz.getDeclaredMethods()){
UseCase usecase = method.getAnnotation(UseCase.class);
if(usecase != null) {
System.out.println("Found use case:" + usecase.id() +" " + usecase.desc());
useCases.remove(new Integer(usecase.id()));
}
}
for (int i : useCases) {
System.out.println("Warning: Missing use case-" + i);
}
}

public static void main(String args[]) {
List<Integer> useCases = new ArrayList<>();
Collections.addAll(useCases, 1, 2, 3, 4, 5);
trackUseCases(useCases, PasswordUtil.class);
}

----------
Found use case:2 no description
Found use case:1 Password must contain at least one numeric
Found use case:3 new password can not equal previously used ones
Warning: Missing use case-4
Warning: Missing use case-5

1.2.1 生成外部文件