注解java如何使用
注解的基本概念
Java注解(Annotation)是一种元数据形式,用于为代码提供附加信息。注解本身不影响代码逻辑,但可以被编译器、开发工具或运行时框架读取并处理。
内置注解
Java提供了一些内置注解,例如:
@Override:标记方法重写父类或接口的方法。@Deprecated:标记已过时的类、方法或字段。@SuppressWarnings:抑制编译器警告。
@Override
public String toString() {
return "Example";
}
自定义注解
通过 @interface 关键字定义注解,可以指定元注解(如 @Retention)控制注解的生命周期和作用范围。
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CustomAnnotation {
String value() default "default";
int priority() default 1;
}
注解的使用
将注解应用于类、方法或字段,并通过反射在运行时读取注解信息。
@CustomAnnotation(value = "test", priority = 2)
public void annotatedMethod() {
System.out.println("Method with annotation");
}
// 反射读取注解
Method method = obj.getClass().getMethod("annotatedMethod");
CustomAnnotation annotation = method.getAnnotation(CustomAnnotation.class);
System.out.println(annotation.value()); // 输出 "test"
注解的保留策略
通过 @Retention 指定注解的保留期限:
RetentionPolicy.SOURCE:仅保留在源码中,编译时丢弃。RetentionPolicy.CLASS:保留到字节码文件,但运行时不可见。RetentionPolicy.RUNTIME:运行时可通过反射读取。
注解的目标范围
通过 @Target 指定注解可应用的目标类型,例如:
ElementType.TYPE:类、接口或枚举。ElementType.METHOD:方法。ElementType.FIELD:字段。
注解的默认值
在定义注解时,可以为元素指定默认值,使用时无需显式赋值。

public @interface DefaultAnnotation {
String key() default "key";
int count() default 0;
}
@DefaultAnnotation
public void defaultMethod() {}






