JAVA之反射學習3-反射獲取成員變數並賦值

qq_42265608發表於2020-12-01
  1. 獲取變數方法
    1.Field[] getFields() 返回所有公共成員變數物件的陣列
    剩下的與前面獲取方法的方法類似
    2.賦值
    void set(Object obj,Object value)
    給obj物件的成員變數賦值為Value,

  2. 例項

 //獲取Class物件
        Class<?> c = Class.forName("com.itheima_02.Student");

        //Student s = new Student();
        Constructor<?> con = c.getConstructor();
        Object obj = con.newInstance();
        System.out.println(obj);

        //s.name = "林青霞";
//        Field nameField = c.getField("name"); //NoSuchFieldException: name
        Field nameField = c.getDeclaredField("name");
        nameField.setAccessible(true);
        nameField.set(obj, "林青霞");
        System.out.println(obj);

        //s.age = 30;
        Field ageField = c.getDeclaredField("age");
        ageField.setAccessible(true);
        ageField.set(obj,30);
        System.out.println(obj);

        //s.address = "西安";
        Field addressField = c.getDeclaredField("address");
        addressField.setAccessible(true);
        addressField.set(obj,"西安");
        System.out.println(obj);

相關文章