租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

java中怎么自定义注解详解,java怎么自定义变量

发布时间:2023-10-28 02:14:31

java中怎样自定义注解详解

在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()方法都被成功地标记为需要记录日志的方法。