★17.注解

简介

  • 注解括号内的称之为 元素
  • 没有元素的注解称为 标记注解

标准注解

  • @Override:声明覆盖。
  • @Deprecated:声明弃用。
  • @SuppressWarnings:声明屏蔽警告。

元注解

  • @Target:决定在何处使用该注解。
  • @Retention:决定哪一个时期该注解起作用。
  • @Documented
  • @Inherited:允许子类继承父类中的注解。

简单示例

定义注解

  • default后接默认值。
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface UseCase {
    int value() default 20;
    int id() default 10;
    String description() default "no description";
}

使用注解

class PasswordUtils {
    @UseCase(id = 47, description = "Passwords must contain at least one numeric")
    public boolean validatePassword(String password) { return (password.matches("\\w*\\d\\w*")); }

    // 如果注解中定义了value,并且在应用注解时只需要为此value赋值,则可以不采用名-值对的语法赋值
    @UseCase(48)
    public String encryptPassword(String password) { return new StringBuilder(password).reverse().toString(); }

    @UseCase(id = 49, description = "New passwords can't equal previously used ones")
    public boolean checkForNewPassword(List prevPasswords, String password) {
        return !prevPasswords.contains(password);
    }
}

注解处理器

public class UseCaseTracker {
    private static void trackUseCases(List useCases, Class cl) {
        for (Method m : cl.getDeclaredMethods()) {
            UseCase uc = m.getAnnotation(UseCase.class);
            if (uc != null) {
                System.out.println("Found Use Case:" + uc.id() + " " + uc.description());
                useCases.remove(new Integer(uc.id()));
            }
        }
        for (int i : useCases) {
            System.out.println("Warning: Missing use case" + i);
        }
    }

    public static void main(String[] args) {
        List useCases = new ArrayList<>();
        Collections.addAll(useCases, 47, 48, 49, 50);
        trackUseCases(useCases, PasswordUtils.class);
    }
}

你可能感兴趣的:(★17.注解)