@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String name() default "";
String value() default "";
}
注解MyAnnotation包含两个属性:name和value,它们的默认值都为空字符串。注解MyAnnotation被@Target和@Retention元注解修饰,表示该注解可以用于修饰方法,且该注解的生命周期为运行时。
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface MyAnnotation {
String name() default "";
String value() default "";
}
注解MyAnnotation被四个元注解修饰,表示该注解可以用于修饰方法,且该注解的生命周期为运行时,可以被javadoc等工具记录到文档中,可以被继承。
public class Test {
@MyAnnotation(name = "test", value = "hello world")
public void test() {
// do something
}
}
在上述例子中,注解MyAnnotation被用来修饰test方法。可以通过反射机制来获取该注解的信息,如下所示:
public class Main {
public static void main(String[] args) {
Method[] methods = Test.class.getDeclaredMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
System.out.println(annotation.name());
System.out.println(annotation.value());
}
}
}
}
在上述例子中,首先获取Test类中所有声明的方法,然后遍历每个方法,如果该方法被MyAnnotation注解修饰,则获取该注解的信息。
public class Main {
public static void main(String[] args) {
Class> clazz = Test.class;
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
Annotation[] annotations = method.getDeclaredAnnotations();
for (Annotation annotation : annotations) {
if (annotation instanceof MyAnnotation) {
MyAnnotation myAnnotation = (MyAnnotation) annotation;
System.out.println(myAnnotation.name());
System.out.println(myAnnotation.value());
}
}
}
}
}
在上述例子中,首先获取Test类的Class对象,然后获取该类中所有声明的方法,遍历每个方法,获取该方法上的所有注解,再遍历每个注解,如果该注解是MyAnnotation注解,则获取该注解的信息。
@MyAnnotation(name = "test", value = "hello world")
public class Test {
// do something
}
在上述例子中,注解MyAnnotation被用来修饰Test类,编译时会生成相应的class文件。
本文介绍了Java中注解的作用和自定义注解的实现方法,包括注解的定义、元注解、注解的使用、反射机制和注解的编译过程。通过本文的学习,读者可以深入理解注解在Java中的应用。本文为翻滚的胖子原创文章,转载无需和我联系,但请注明来自猿教程iskeys.com
