当前位置:网站首页>Annotation初体验

Annotation初体验

2022-07-06 23:23:00 菜鸟xiaowang

1.定义注解

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Person {

    String name() default "abc";
    int age() default 20;
}

2.使用注解

public class Student {
    @Person(name = "王xx",age = 30)
    public Object person;
}

3.处理注解

public class PersonUtils {
    public static void getPersonInfo(Class<?> clazz){
        for (Field declaredField : clazz.getDeclaredFields()) {
            if (declaredField.isAnnotationPresent(Person.class)){
                Person person = declaredField.getAnnotation(Person.class);
                System.out.println("name:"+person.name()+"age"+person.age());
            }
        }
    }
}

4.测试

PersonUtils.getPersonInfo(Student.class);

5.结果

 

原网站

版权声明
本文为[菜鸟xiaowang]所创,转载请带上原文链接,感谢
https://blog.csdn.net/xiaowang_lj/article/details/125639887