Z
ZHANK
反射与注解

注解入门

理解 @Override、@Deprecated 等内置注解,定义自己的注解

注解

注解是 Java 的元数据机制,在编译、运行时提供额外信息。

学完本章你将: 理解内置注解、元注解、自定义注解。


内置注解

java
// @Override —— 检查是否重写了父类方法
@Override
public String toString() {
    return "MyClass";
}

// @Deprecated —— 标记已过时
@Deprecated
public void oldMethod() {
    // 旧方法
}

// @SuppressWarnings —— 抑制警告
@SuppressWarnings("unchecked")
List<String> list = (List<String>) someRawList;

// @FunctionalInterface —— 标记函数式接口
@FunctionalInterface
interface Calculator {
    int calc(int a, int b);
}

元注解

java
import java.lang.annotation.*;

// 定义注解
@Target(ElementType.METHOD)   // 可用在方法上
@Retention(RetentionPolicy.RUNTIME) // 运行时保留
public @interface Test {
    int timeout() default 0;  // 带默认值的属性
}

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.SOURCE)
public @interface Author {
    String name();
    String date();
}

自定义注解

java
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
    String name();
}

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {
    String name();
    boolean nullable() default true;
}

// 使用
@Table(name = "users")
public class User {
    @Column(name = "user_name")
    private String name;

    @Column(name = "age", nullable = false)
    private int age;
}

// 通过反射读取注解
Class<User> clazz = User.class;
Table table = clazz.getAnnotation(Table.class);
System.out.println(table.name()); // "users"