如何注解java
注解的基本概念
Java注解(Annotation)是一种元数据形式,用于为代码提供附加信息。注解不会直接影响代码逻辑,但可以被编译器、开发工具或运行时环境处理。
内置注解类型
Java提供了一些内置注解:
@Override:标记方法覆盖父类方法@Deprecated:标记已过时的元素@SuppressWarnings:抑制编译器警告@SafeVarargs:断言方法或构造函数不会对其可变参数执行不安全操作@FunctionalInterface:标记接口为函数式接口
自定义注解
创建自定义注解需要使用@interface关键字:
public @interface CustomAnnotation {
String value() default "default";
int count() default 0;
}
元注解
元注解用于注解其他注解:
@Target:指定注解可以应用的元素类型@Retention:指定注解保留策略@Documented:标记注解包含在Javadoc中@Inherited:允许子类继承父类的注解@Repeatable:允许在同一元素上重复使用注解
注解的使用示例
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
String author() default "unknown";
String date();
}
public class TestClass {
@TestAnnotation(author = "John", date = "2023-01-01")
public void testMethod() {
// 方法实现
}
}
运行时处理注解
通过反射API可以在运行时处理注解:
Method method = TestClass.class.getMethod("testMethod");
TestAnnotation annotation = method.getAnnotation(TestAnnotation.class);
if (annotation != null) {
System.out.println("Author: " + annotation.author());
System.out.println("Date: " + annotation.date());
}
注解参数类型限制
注解参数只能是以下类型:
- 基本数据类型(int、float等)
- String
- Class
- 枚举类型
- 其他注解类型
- 以上类型的数组
注解保留策略
通过@Retention指定注解保留期:
RetentionPolicy.SOURCE:仅保留在源文件中RetentionPolicy.CLASS:保留在class文件中(默认)RetentionPolicy.RUNTIME:保留到运行时
注解目标限制
通过@Target限制注解可以应用的位置:
ElementType.TYPE:类、接口、枚举ElementType.FIELD:字段ElementType.METHOD:方法ElementType.PARAMETER:参数ElementType.CONSTRUCTOR:构造器ElementType.LOCAL_VARIABLE:局部变量ElementType.ANNOTATION_TYPE:注解类型ElementType.PACKAGE:包ElementType.TYPE_PARAMETER:类型参数ElementType.TYPE_USE:类型使用
重复注解
使用@Repeatable实现重复注解:

@Repeatable(Authorities.class)
public @interface Authority {
String role();
}
public @interface Authorities {
Authority[] value();
}
@Authority(role="admin")
@Authority(role="user")
public class User {
}






