要封装一个注解,需要使用注解的元注解来定义注解的属性和使用方式。

以下是一个简单的封装注解的例子:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyAnnotation {
    String name() default '';
    int version() default 1;
}

这个注解有两个属性,一个是'name',一个是'version',可以通过'default'设置默认值。@Retention(RetentionPolicy.RUNTIME)表示注解的生命周期为运行时,可以通过反射读取;@Target(ElementType.TYPE)表示注解只能用于类上。

可以在类上使用这个注解:

@MyAnnotation(name = 'test', version = 2)
public class MyClass {
    // class body
}

在程序中可以通过反射读取注解的值:

MyAnnotation annotation = MyClass.class.getAnnotation(MyAnnotation.class);
String name = annotation.name(); // 'test'
int version = annotation.version(); // 2
Java 注解封装:自定义注解示例

原文地址: https://www.cveoy.top/t/topic/op6X 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录