JAVA自定义注解

 

import java.lang.annotation.*;
 
// 定义一个自定义注解
public @interface MyAnnotation {
    // 在注解中定义属性
    String value() default "";
}
 
// 使用自定义注解
class MyClass {
    
    // 在类上应用自定义注解
    @MyAnnotation(value = "Hello")
    public void myMethod(){
        System.out.println("This is a method with custom annotation.");
    }
}
 
// 获取并处理自定义注解信息
public class MainClass {
    public static void main(String[] args) throws NoSuchMethodException {
        
        // 获取myMethod方法上的所有注解
        Annotation[] annotations = MyClass.class.getDeclaredMethod("myMethod").getAnnotations();
        
        for (Annotation annotation : annotations){
            if (annotation instanceof MyAnnotation){
                MyAnnotation myAnnotation = (MyAnnotation) annotation;
                
                // 输出注解的值
                System.out.println("Value of the annotation: " + myAnnotation.value());
            }
        }
    }
}

结束!

 

posted @ 2024-01-18 10:34  aaronthon  阅读(6)  评论(0编辑  收藏  举报