简介
- 注解括号内的称之为 元素 。
- 没有元素的注解称为 标记注解 。
标准注解
-
@Override:声明覆盖。
-
@Deprecated:声明弃用。
-
@SuppressWarnings:声明屏蔽警告。
元注解
-
@Target:决定在何处使用该注解。
-
@Retention:决定哪一个时期该注解起作用。
-
@Documented:
-
@Inherited:允许子类继承父类中的注解。
简单示例
定义注解
@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<String> prevPasswords, String password) {
return !prevPasswords.contains(password);
}
}
注解处理器
public class UseCaseTracker {
private 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());
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<Integer> useCases = new ArrayList<>();
Collections.addAll(useCases, 47, 48, 49, 50);
trackUseCases(useCases, PasswordUtils.class);
}
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。