上节中简单介绍了几个java原生注解,根据这些原生注解派生出了许多用户自定义注解,这节来了解下如何制作简单的自定义注解,前一节介绍java原生注解可以点此跳转。
获取注解
根据上节中的知识,已经可以自定义注解了,但自定义注解只能标注在相应的代码中,并没有起到实际的作用,要将注解及注解的内容获取和逻辑处理才能发挥注解的真正作用。
java中当然提供了相应的方法,获取注解属于反射的一种,java.lang.reflect.AnnotatedElement接口可以通过反射读取出注解,反射包中的AccessibleObjec,Class,Constructor,Field,Method,Package都继承于AnnotatedElement,都具有通过反射读取注解的能力。
AnnotatedElement中的方法简介如下。
方法 | 返回值 | 方法描述 |
---|---|---|
getAnnotation(Class<T> annotationClass) | <T extends Annotation> T | 如果指定注解存在元素上,返回指定注解,否则返回null |
getAnnotations() | Annotation[] | 返回存在于元素上的所有注解 |
getDeclaredAnnotations() | Annotation[] | 返回直接存在于元素上的所有元素 |
isAnnotationPresent(Class<? extends Annotation> annotationClass) | boolean | 如果指定注解类型出现在元素上,返回true,否则返回false |
AnnotatedElement可以通过这几个方法获取和判断元素上的注解,重点解释下getDeclaredAnnotations方法,直接存在于元素上的注解是指此注解不是通过继承产生的,这四个方法的详情可以点击此处查看。
代码实现
了解了获取注解的方法,就可以用代码来实现自定义注解的功能。
- 自定义注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AnimalName {
String value() default "";
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AnimalColor {
public enum Color{RED, BLUE, YELLOW};
Color color() default Color.YELLOW;
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AnimalOwner {
String name() default "";
String address() default "";
}
- 在相应代码处标记注解
public class Dog {
@AnimalName("Clob")
private String name;
@AnimalColor(color = AnimalColor.Color.BLUE)
private String color;
@AnimalOwner(name = "Cloneable", address = "China")
private String owner;
}
- 利用AnnotatedElement的方法获取注解并进行相应处理
public class AnimalAnnoUtil {
public static void printAnimalInfo(Class clazz) {
Field[] fields = clazz.getDeclaredFields();
for(Field field : fields) {
if(field.isAnnotationPresent(AnimalName.class)) {
AnimalName animalName = field.getAnnotation(AnimalName.class);
System.out.println("Animal name is " + animalName.value());
} else if(field.isAnnotationPresent(AnimalColor.class)) {
AnimalColor animalColor = field.getAnnotation(AnimalColor.class);
System.out.println("Animal color is " + animalColor.color());
} else if(field.isAnnotationPresent(AnimalOwner.class)) {
AnimalOwner animalOwner = field.getAnnotation(AnimalOwner.class);
System.out.println("Animal's owner is " + animalOwner.name() + ", his address is " + animalOwner.address());
}
}
}
}
- 调用测试
public static void main(String[] args) {
AnimalAnnoUtil.printAnimalInfo(Dog.class);
}
利用AnnotatedElement的方法获取注解并进行相应处理这步,通过反射获取类的Field,遍历Field时使用AnnotatedElement的方法就可以判断和获取元素上的annotation,根据注解中的值以及注解就可以进行相应的逻辑处理。
可点击此处查看详细代码。
网友评论