面试题答案
一键面试- 声明注解:
- 使用
@interface
关键字来声明一个注解。 - 可以在注解中定义成员变量,成员变量以无参数方法的形式定义。
- 使用
- 使用元注解:
@Retention
:指定注解的保留策略,有RetentionPolicy.SOURCE
(仅在源文件中保留,编译后丢弃)、RetentionPolicy.CLASS
(编译后保留在字节码文件中,但运行时不会加载到 JVM 中,默认值)、RetentionPolicy.RUNTIME
(运行时也保留,可以通过反射获取)。@Target
:指定注解可以应用的目标元素,如ElementType.TYPE
(类、接口等类型)、ElementType.METHOD
(方法)、ElementType.FIELD
(字段)等。
- 示例代码:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
// 自定义文档生成注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
@interface DocumentedInfo {
String description();
String author();
int version() default 1;
}
// 在类上使用注解
@DocumentedInfo(description = "这是一个示例类", author = "张三", version = 1)
class ExampleClass {
// 在字段上使用注解
@DocumentedInfo(description = "这是一个示例字段", author = "李四")
private int exampleField;
// 在方法上使用注解
@DocumentedInfo(description = "这是一个示例方法", author = "王五")
public void exampleMethod() {
// 方法体
}
}
在上述代码中:
- 首先定义了
DocumentedInfo
注解,使用了@Retention
元注解指定保留策略为运行时保留,使用@Target
元注解指定可以应用在类、方法和字段上。 - 该注解定义了
description
、author
两个必填成员变量,以及version
一个有默认值的成员变量。 - 然后在
ExampleClass
类、exampleField
字段和exampleMethod
方法上使用了这个自定义注解。