← 返回首页

Java注解:元数据的强大力量

📂 java ⏱ 2 min 230 words

Java注解:元数据的强大力量

概述

注解(Annotation)是Java的元数据机制,它可以在代码中添加信息,用于编译检查、运行时处理等。

1. 内置注解

public class AnnotationDemo {
    @Override
    public String toString() {
        return "AnnotationDemo";
    }

    @Deprecated
    public void oldMethod() {
        System.out.println("已废弃的方法");
    }

    @SuppressWarnings("unchecked")
    public void uncheckedMethod() {
        List list = new ArrayList();
        list.add("Hello");
    }
}

2. 元注解

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {
    String value() default "";
    String level() default "INFO";
}

3. 自定义注解

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NotNull {
    String message() default "不能为空";
}

public class User {
    @NotNull(message = "用户名不能为空")
    private String username;

    @NotNull(message = "密码不能为空")
    private String password;
}

public class ValidationProcessor {
    public static void validate(Object obj) throws Exception {
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(NotNull.class)) {
                field.setAccessible(true);
                Object value = field.get(obj);
                if (value == null) {
                    NotNull annotation = field.getAnnotation(NotNull.class);
                    throw new IllegalArgumentException(annotation.message());
                }
            }
        }
    }
}

4. 运行时注解处理

import java.lang.annotation.*;
import java.lang.reflect.Method;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogAction {
    String action();
}

public class LogProcessor {
    public static void process(Object obj) {
        Method[] methods = obj.getClass().getDeclaredMethods();
        for (Method method : methods) {
            if (method.isAnnotationPresent(LogAction.class)) {
                LogAction annotation = method.getAnnotation(LogAction.class);
                System.out.println("方法: " + method.getName() + ", 操作: " + annotation.action());
            }
        }
    }
}

5. Spring中的注解

@Service
public class SpringAnnotationDemo {
    @Autowired
    private UserRepository userRepository;

    @GetMapping("/users/{id}")
    public User getUser(@PathVariable Long id) {
        return userRepository.findById(id).orElse(null);
    }
}

最佳实践

  1. 合理使用注解:不要过度使用
  2. 设置默认值:为注解元素设置默认值
  3. 使用@Target:限制注解的使用范围
  4. 使用@Retention:控制注解的保留策略
  5. 文档化注解:使用@Documented

总结

注解是Java的元数据机制,掌握注解的定义和使用,可以实现声明式编程,简化代码配置。