Java注解列引
·
一、内置注解(作用于代码)
- @Override
含义:表示子类方法重写了父类或接口的方法。帮助编译器检查方法签名是否正确。
class Animal {
void sound() {}
}
class Dog extends Animal {
@Override
void sound() { } // 正确重写
// @Override
// void sound(int x) {} // 若取消注释,编译错误(不是重写)
}
- @Deprecated
含义:标记元素(类、方法、字段等)已过时,不推荐使用。编译器会警告。
class OldClass {
@Deprecated
void oldMethod() { }
}
public class Test {
public static void main(String[] args) {
new OldClass().oldMethod(); // 编译警告:已过时
}
}
- @SuppressWarnings
含义:抑制编译器警告,常用于忽略未使用的变量、未检查的类型转换等。
import java.util.ArrayList;
import java.util.List;
public class Test {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
List list = new ArrayList(); // 原始类型,会产生未检查警告
list.add("hello"); // 警告被抑制
}
}
- @SafeVarargs
含义:用于断言可变参数方法不会对堆进行污染(即不会将不安全的操作引入泛型)。只能用于 static、final 或私有构造方法。
public class SafeVarargsDemo {
@SafeVarargs
static <T> void print(T... args) {
for (T t : args) System.out.print(t + " ");
}
public static void main(String[] args) {
print("A", "B", "C"); // 无堆污染警告
}
}
- @FunctionalInterface
含义:标记接口为函数式接口(只有一个抽象方法),编译器会检查是否符合规范。
@FunctionalInterface
interface Calculator {
int compute(int a, int b); // 唯一的抽象方法
// 可以有默认方法或静态方法
default void log() { }
}
public class Test {
public static void main(String[] args) {
Calculator add = (a, b) -> a + b;
System.out.println(add.compute(3, 5)); // 8
}
}
二、元注解(用于自定义注解)
元注解是用于定义注解的注解。
- @Retention
含义:指定注解保留到哪个阶段。
RetentionPolicy.SOURCE:只保留在源码中,编译时丢弃(如 @Override)。
RetentionPolicy.CLASS:保留在 .class 文件中,但 JVM 不加载(默认)。
RetentionPolicy.RUNTIME:运行时可通过反射获取。
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation { }
- @Target
含义:限制注解可以修饰的程序元素(类、方法、字段等)。
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target({ElementType.METHOD, ElementType.FIELD})
@interface FieldOrMethod { } // 只能用在方法或字段上
- @Documented
含义:使注解信息包含在 Javadoc 中。
import java.lang.annotation.Documented;
@Documented
@interface DocAnnotation { } // 使用该注解的元素,javadoc 会显示此注解
- @Inherited
含义:允许子类继承父类上的注解(仅对类继承有效,且注解需被 @Retention(RUNTIME) 保留)。
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@interface InheritedAnno { }
@InheritedAnno
class Parent { }
class Child extends Parent { } // Child 也拥有 InheritedAnno
- @Repeatable (Java 8+)
含义:允许同一个注解在同一个位置重复使用。
import java.lang.annotation.Repeatable;
@Repeatable(Scores.class)
@interface Score {
int value();
}
@interface Scores {
Score[] value();
}
@Score(80)
@Score(90)
class Student { } // 重复使用 @Score
三、其他标准注解
@Native (Java 8+)
含义:标记常量字段可以被本地代码(如 C)引用,仅供工具生成头文件使用。
class NativeConstants {
@Native public static final int MAX_SIZE = 1024;
}
更多推荐


所有评论(0)