Java注解

时间:2020-10-18 09:35:17   收藏:0   阅读:22

介绍

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

元注解:
(1)@Target:表示该注解可以用于什么地方,可能的参数包括:

定义注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UseCase {
    public int id();
    public String description() default "no description";
}

使用注解

public class PasswordUtils {
    @UseCase(id=47,description = "Passwords must contain at least one numeric")
    public boolean validatePassword(String password){
        return (password.matches("\\w*\\d\\w*"));
    }
    @UseCase(id=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<String> prevPasswords, String password){
        return !prevPasswords.contains(password);
    }
}

注解处理器

public class UseCaseTracker {
    public static void trackUseCases(List<Integer> 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());
            }
        }
        for (int i:useCases){
            System.out.println("Warning: Missing use case-"+i);
        }
    }
    public static void main(String[] args) {
        List<Integer> useCases = new ArrayList<Integer>();
        Collections.addAll(useCases,47,48,49,50);
        trackUseCases(useCases,PasswordUtils.class);
    }
}

默认值:
(1)元素不能有不确定的值,要么具有默认值,要么使用注解时提供元素的值。
(2)对于非基本类型的元素,无论是定义默认值还是使用时都不能以null作为其值。
(3)可以定义特殊值,比如空字符串""或者负数绕过,表示某元素不存在。

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!