Set field value with reflection

前端 未结 5 752
天涯浪人
天涯浪人 2020-12-01 10:00

I\'m working with one project which is not opensource and I need to modify one or more its classes.

In one class is following collection:

private Map         


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-01 11:01

    You can try this:

    static class Student {
        private int age;
        private int number;
    
        public Student(int age, int number) {
            this.age = age;
            this.number = number;
        }
    
        public Student() {
        }
    }
    public static void main(String[] args) throws IllegalAccessException, NoSuchFieldException {
        Student student1=new Student();
       // Class g=student1.getClass();
        Field[]fields=student1.getClass().getDeclaredFields();
        Field age=student1.getClass().getDeclaredField("age");
        age.setAccessible(true);
        age.setInt(student1,13);
        Field number=student1.getClass().getDeclaredField("number");
        number.setAccessible(true);
        number.setInt(student1,936);
    
        for (Field f:fields
             ) {
            f.setAccessible(true);
    
            System.out.println(f.getName()+" "+f.getInt(student1));
    
        }
    }
    

    }

提交回复
热议问题