代码如下:
package ClassObjectPack;public class Student {private String name;int age;public String address;public Student(String name, int age, String address) {this.name = name;this.age = age;this.address = address;}public Student() {}private Student(String name) {this.name = name;}Student(String name, int age) {this.name = name;this.age = age;}private void function(){System.out.println("function");}public void method1(){System.out.println("method");}public void method2(String s){System.out.println("method:"+s);}public String method3(String s,int i){return s+","+i;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +", address='" + address + '\'' +'}';}
}
package ClassObjectPack01;import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;public class ReflectDemo04 {public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {Class<?> c = Class.forName("ClassObjectPack.Student");Constructor<?> con = c.getConstructor();Object obj = con.newInstance();System.out.println(obj);//getField只能拿公共的
// Field nameFiled = c.getField("name");Field nameField = c.getDeclaredField("name");nameField.setAccessible(true);nameField.set(obj,"林青霞");System.out.println(obj);System.out.println("--------------------------");//s.age = 30Field ageField = c.getDeclaredField("age");ageField.setAccessible(true);ageField.set(obj,30);System.out.println(obj);Field addressField = c.getDeclaredField("address");addressField.setAccessible(true);//可有可无addressField.set(obj,"西安");System.out.println(obj);}}
测试结果: