学堂 学堂 学堂公众号手机端

要自定义注解,首先需要使用@interface关键字来定义一个注解,然后在需要使用注解的地方使用该注解即可

lewis 1年前 (2024-03-27) 阅读数 7 #技术

要自定义注解,首先需要使用@interface关键字来定义一个注解,然后在需要使用注解的地方使用该注解即可。

示例代码如下:

//自定义注解 public@interfaceMyAnnotation{ Stringvalue(); } //使用注解 @MyAnnotation(value="Hello") publicclassMyClass{ publicstaticvoidmain(String[]args){ MyClassmyClass=newMyClass(); //获取注解的值 MyAnnotationannotation=MyClass.class.getAnnotation(MyAnnotation.class); System.out.println(annotation.value());//输出:Hello } }

在上面的示例中,首先定义了一个名为MyAnnotation的自定义注解,然后在MyClass类上使用了这个注解,并且给注解的value属性赋值为"Hello"。在main方法中通过反射获取MyClass类上的MyAnnotation注解,并输出其值。


版权声明

本文仅代表作者观点,不代表博信信息网立场。

热门