美文网首页
java 注解

java 注解

作者: 月巴大叔 | 来源:发表于2023-03-19 22:11 被阅读0次

    Annotation 注解修饰

    @Rentention (注解的保留时间,SOURCE(源码)、CLASS(编译)、RUNTIME(运行时))默认为CLASS
    @Documented:是否会保存到javadoc文档中
    @Target:用来修饰哪些程序的元素,如 TYPE,METHOD,CONSTRUCTOR、FILED、PARAMETER

    自定义一个注解类 @UserGroup

    @Retention(RetentionPolicy.RUNTIME)
    @Target({ELementType.FIELD,ElementType.METHOD})
    public @interface UserGroup{
           int age();
    }
    

    然后接下来就是调用

    @Slf4j
    public class TestAnnotation {
      @UserGroup(age = 20)
      private int age;
            
      public int setAge(int age){
            this.age = age;
            log.info("\n" + "age : " + this.age);
            return this.age;
        }
    
    public static void  main(String[] args)throws InstantiationException, IllegalAccessException,InvocationTargetException,NoSuchMethodException{
            TestAnnotation testAnnotation = new TestAnnotation();
            testAnnotation.setage();
        } 
    
    public void  setage() throws InstantiationException, IllegalAccessException,NoSuchMethodException, InvocationTargetException {
            Class class1 = TestAnnotation.class;
            for (Field field:class1.getDeclaredFields()){
                if(field.isAnnotationPresent(UserGroup.class)){
                    UserGroup annotation = field.getAnnotation(UserGroup.class);
                    int age1 = annotation.age();
                    Method method = class1.getDeclaredMethod("setAge", int.class);
                    method.invoke(class1.newInstance(),age1);
                }
            }
        }
    
    age

    相关文章

      网友评论

          本文标题:java 注解

          本文链接:https://www.haomeiwen.com/subject/syoyrdtx.html