MST

星途 面试题库

面试题:Java中如何通过反射获取类上的注解

在Java反射机制中,给定一个类,描述如何使用反射获取该类上定义的自定义注解,并给出示例代码。
42.2万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
  1. 获取类上定义的自定义注解步骤
    • 使用Class类的getAnnotation(Class<T> annotationClass)方法,该方法用于获取指定类型的注解,如果该类没有指定类型的注解,则返回null
    • annotationClass参数是你自定义注解的类对象。
  2. 示例代码
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)
@interface MyAnnotation {
    String value();
}

// 定义使用注解的类
@MyAnnotation("This is a test")
class MyClass {
}

public class ReflectionAnnotationExample {
    public static void main(String[] args) {
        // 获取MyClass的Class对象
        Class<MyClass> myClass = MyClass.class;
        // 获取MyClass类上的MyAnnotation注解
        MyAnnotation annotation = myClass.getAnnotation(MyAnnotation.class);
        if (annotation != null) {
            System.out.println("注解值: " + annotation.value());
        } else {
            System.out.println("MyClass类上没有MyAnnotation注解");
        }
    }
}

这段代码首先定义了一个自定义注解MyAnnotation,并将其应用在MyClass类上。然后在main方法中,通过反射获取MyClass类上的MyAnnotation注解,并输出注解的值。如果没有找到注解,则输出相应提示。