要自定义注解,首先需要使用@interface关键字来定义一个注解,然后在需要使用注解的地方使用该注解即可。
示例代码如下:
// 自定义注解public @interface MyAnnotation { String value();}// 使用注解@MyAnnotation(value = "Hello")public class MyClass { public static void main(String[] args) { MyClass myClass = new MyClass(); // 获取注解的值 MyAnnotation annotation = MyClass.class.getAnnotation(MyAnnotation.class); System.out.println(annotation.value()); // 输出:Hello }}在上面的示例中,首先定义了一个名为MyAnnotation的自定义注解,然后在MyClass类上使用了这个注解,并且给注解的value属性赋值为"Hello"。在main方法中通过反射获取MyClass类上的MyAnnotation注解,并输出其值。


