当前位置:网站首页>Operate attribute chestnut through reflection

Operate attribute chestnut through reflection

2022-06-23 02:08:00 Doghead Intern

 public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        Class student = Student.class;

        // Get a parameterless construction object through reflection 
        Student s1 = (Student) student.newInstance();
        System.out.println(s1);

        // Get a parameterized construction object through reflection 
        Constructor constructor = student.getConstructor(Integer.class, String.class, int.class);
        Student s2 = (Student) constructor.newInstance(18, " Xiaohong ", 1);
        System.out.println(s2);

        // Call normal methods through reflection 
        // Get an object first 
        Student s3 = (Student) student.newInstance();
        // Get a way 
        Method setName = student.getDeclaredMethod("setName", String.class);
        //invoke: Activate ( object , The value of the method )
        setName.invoke(s3," Red red ");
        System.out.println(s3.getName());

        // Manipulate attributes by reflection 
        Student s4 = (Student) student.newInstance();
        Field name = student.getDeclaredField("name");
        /// Private properties cannot be manipulated directly 
        // Turn off security detection 
        name.setAccessible(true);
        name.set(s4," Sensitive ");
        System.out.println(s4.getName());
    }

原网站

版权声明
本文为[Doghead Intern]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202220502150716.html