parameter获取注解名称
时间: 2023-10-04 13:10:47 浏览: 237
在 Java 中,获取方法或类上的注解名称可以使用反射机制。具体步骤如下:
1. 通过 Class 对象获取方法或类的 Method 或 Class 对象。
2. 使用 Method 或 Class 对象的 getAnnotation(Class<T> annotationClass) 方法获取指定类型的注解对象。
3. 使用注解对象的 annotationType() 方法获取注解对象的 Class 对象。
4. 使用 Class 对象的 getName() 方法获取注解对象的名称。
示例代码如下:
```java
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@interface MyAnnotation {
String value();
}
@MyAnnotation("test")
public class MyClass {
@MyAnnotation("testMethod")
public void myMethod() {
// do something
}
}
public class Main {
public static void main(String[] args) throws NoSuchMethodException {
Class<MyClass> clazz = MyClass.class;
// 获取类上的注解名称
MyAnnotation classAnnotation = clazz.getAnnotation(MyAnnotation.class);
String classAnnotationName = classAnnotation.annotationType().getName();
System.out.println("Class Annotation Name: " + classAnnotationName);
// 获取方法上的注解名称
Method method = clazz.getMethod("myMethod");
MyAnnotation methodAnnotation = method.getAnnotation(MyAnnotation.class);
String methodAnnotationName = methodAnnotation.annotationType().getName();
System.out.println("Method Annotation Name: " + methodAnnotationName);
}
}
```
运行以上代码,输出结果如下:
```
Class Annotation Name: MyAnnotation
Method Annotation Name: MyAnnotation
```
阅读全文
相关推荐


















