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