面试题答案
一键面试创建Java自定义注解
- 定义注解:使用
@interface
关键字来定义自定义注解。注解可以包含成员变量(也称为属性),这些成员变量在使用注解时需要赋值,除非它们有默认值。
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)
public @interface MyAnnotation {
String value() default "";
int number() default 0;
}
@Retention(RetentionPolicy.RUNTIME)
:表示该注解在运行时存在,这样在运行时可以通过反射获取到注解信息。@Target(ElementType.TYPE)
:表示该注解可以应用在类上。如果需要应用在方法、字段等其他元素上,可以修改ElementType
的值。
在类中使用自定义注解
在类声明前使用自定义注解,并为注解的属性赋值(如果属性没有默认值)。
@MyAnnotation(value = "示例值", number = 10)
public class MyClass {
// 类的内容
}
通过反射获取类上的自定义注解信息
在Java中,可以使用反射来获取类上的注解信息。
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class AnnotationReflection {
public static void main(String[] args) {
try {
Class<?> clazz = Class.forName("MyClass");
MyAnnotation annotation = clazz.getAnnotation(MyAnnotation.class);
if (annotation != null) {
System.out.println("注解的value值: " + annotation.value());
System.out.println("注解的number值: " + annotation.number());
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Class.forName("MyClass")
:通过类名获取Class
对象。clazz.getAnnotation(MyAnnotation.class)
:获取类上指定类型的注解。- 如果获取到注解对象,就可以访问注解的属性值。
通过上述步骤,就完成了创建自定义注解、在类中使用注解以及通过反射获取注解信息的过程。