代码如下:
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.constant.DynamicCallSiteDesc;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;public class ReflectDemo03 {public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {Class<?> c = Class.forName("ClassObjectPack.Student");// Field getField(String name)
// 返回一个 Field对象,它反映此表示的类或接口的指定公共成员字段 类对象。
// Field[] getFields()
// 返回包含一个数组 Field对象反射由此表示的类或接口的所有可访问的公共字段 类对象。// Field getDeclaredField(String name)
// 返回一个 Field对象,它反映此表示的类或接口的指定已声明字段 类对象。
// Field[] getDeclaredFields()
// 返回的数组 Field对象反映此表示的类或接口声明的所有字段 类对象。Field[] fields = c.getFields();for (Field field:fields){System.out.println(field);}System.out.println("-----------------------------------");Field[] fields01 = c.getDeclaredFields();for (Field field:fields01){System.out.println(field);}System.out.println("--------------------------------------");Field addressField = c.getField("address");//获取无参构造方法创建对象Constructor<?> con = c.getConstructor();Object obj = con.newInstance();addressField.set(obj,"西安");System.out.println(obj);}
}
测试结果: