面试题答案
一键面试- 获取类上定义的自定义注解步骤:
- 使用
Class
类的getAnnotation(Class<T> annotationClass)
方法,该方法用于获取指定类型的注解,如果该类没有指定类型的注解,则返回null
。 annotationClass
参数是你自定义注解的类对象。
- 使用
- 示例代码:
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
注解,并输出注解的值。如果没有找到注解,则输出相应提示。