java如何标注
在Java中,标注(Annotation)是一种元数据形式,用于为代码提供附加信息。以下是常见的标注用法和示例:
内置标注
Java提供了一些内置标注,常用于代码标记或编译器指令:

@Override
public void methodName() {} // 表示方法重写父类方法
@Deprecated
public void oldMethod() {} // 标记方法已过时
@SuppressWarnings("unchecked")
List<String> list = new ArrayList(); // 抑制编译器警告
自定义标注
通过@interface关键字可以定义自定义标注:
// 定义标注
public @interface CustomAnnotation {
String value() default "default";
int priority() default 0;
}
// 使用标注
@CustomAnnotation(value = "example", priority = 1)
public class AnnotatedClass {}
元标注
用于标注其他标注的元标注(Meta-annotation):

@Target(ElementType.METHOD) // 指定标注适用于方法
@Retention(RetentionPolicy.RUNTIME) // 标注在运行时保留
public @interface MethodAnnotation {}
运行时处理标注
通过反射机制可以在运行时处理标注:
Method method = obj.getClass().getMethod("methodName");
if (method.isAnnotationPresent(CustomAnnotation.class)) {
CustomAnnotation annot = method.getAnnotation(CustomAnnotation.class);
System.out.println(annot.value());
}
标注参数限制
标注参数只能是基本类型、String、Class、枚举、其他标注或这些类型的数组:
public @interface ComplexAnnotation {
Class<?> targetClass();
String[] tags();
RetentionPolicy policy() default RetentionPolicy.CLASS;
}
标注在Java中广泛用于框架开发(如Spring)、代码生成和文档生成等场景。合理使用标注可以增强代码的可读性和可维护性。






