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 @   aaronthon  阅读(22)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 字符编码:从基础到乱码解决
历史上的今天:
2022-01-18 CentOS7搭建k8s集群
2018-01-18 面想对象的三大特性之多态和封装
2018-01-18 抽象类与接口类
2018-01-18 面向对象的三大特性之继承
点击右上角即可分享
微信分享提示