MST

星途 面试题库

面试题:Java中如何通过反射获取注解信息

假设你定义了一个自定义注解`@MyAnnotation`,并将其应用在类、方法或者字段上。请编写Java代码,通过反射机制获取这些元素上的`@MyAnnotation`注解实例,并打印出注解中的属性值。
38.7万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

// 定义自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
@interface MyAnnotation {
    String value() default "";
}

// 测试类
class TestClass {
    @MyAnnotation("field value")
    private String field;

    @MyAnnotation("method value")
    public void testMethod() {}
}

public class AnnotationReflectionExample {
    public static void main(String[] args) {
        try {
            // 获取类的注解
            Class<TestClass> testClass = TestClass.class;
            MyAnnotation classAnnotation = testClass.getAnnotation(MyAnnotation.class);
            if (classAnnotation != null) {
                System.out.println("Class annotation value: " + classAnnotation.value());
            }

            // 获取方法的注解
            Method method = testClass.getMethod("testMethod");
            MyAnnotation methodAnnotation = method.getAnnotation(MyAnnotation.class);
            if (methodAnnotation != null) {
                System.out.println("Method annotation value: " + methodAnnotation.value());
            }

            // 获取字段的注解
            Field field = testClass.getDeclaredField("field");
            MyAnnotation fieldAnnotation = field.getAnnotation(MyAnnotation.class);
            if (fieldAnnotation != null) {
                System.out.println("Field annotation value: " + fieldAnnotation.value());
            }
        } catch (NoSuchMethodException | NoSuchFieldException e) {
            e.printStackTrace();
        }
    }
}
  1. 定义自定义注解@MyAnnotation
    • 使用@Retention(RetentionPolicy.RUNTIME)确保注解在运行时可用。
    • 使用@Target指定注解可以应用在类、方法和字段上。
    • 定义一个value属性,默认值为空字符串。
  2. 定义测试类TestClass
    • 为字段field添加@MyAnnotation注解,并设置属性值。
    • 为方法testMethod添加@MyAnnotation注解,并设置属性值。
  3. main方法中通过反射获取注解实例并打印属性值
    • 使用Class.getAnnotation获取类上的注解。
    • 使用Method.getAnnotation获取方法上的注解。
    • 使用Field.getAnnotation获取字段上的注解。
    • 打印注解中的value属性值。