温馨提示×

java中怎么自定义注解详解

小亿
95
2023-10-28 02:14:31
栏目: 编程语言

在Java中,可以使用@interface关键字来定义注解。自定义注解的语法如下:

public @interface CustomAnnotation {
    String value() default "";
    int number() default 0;
}

在自定义注解中,可以定义多个成员变量,并为这些成员变量指定默认值。成员变量的类型可以是基本类型、String、枚举、Class、注解或它们的数组。

自定义注解可以通过元注解来为注解添加元数据,常见的元注解有@Retention@Target@Documented@Inherited等。

下面是一个使用自定义注解的示例:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Log {
    String value();
}

public class MyClass {
    @Log("methodA")
    public void methodA() {
        // 方法体
    }

    @Log("methodB")
    public void methodB() {
        // 方法体
    }
}

public class Main {
    public static void main(String[] args) {
        MyClass myClass = new MyClass();
        Method[] methods = myClass.getClass().getMethods();
        for (Method method : methods) {
            if (method.isAnnotationPresent(Log.class)) {
                Log annotation = method.getAnnotation(Log.class);
                System.out.println(annotation.value());
            }
        }
    }
}

在上述示例中,@Log是一个自定义注解,用于标记需要记录日志的方法。MyClass类中的methodA()methodB()方法都使用了@Log注解进行标记。

Main类中,通过反射获取MyClass类的所有方法,并使用isAnnotationPresent()方法判断方法是否使用了@Log注解。如果使用了@Log注解,则通过getAnnotation()方法获取注解的值。

运行以上代码,输出结果为:

methodA
methodB

这说明methodA()methodB()方法都被成功地标记为需要记录日志的方法。

0