package com.yjf.esupplier.common.test;import java.lang.reflect.Constructor;import java.lang.reflect.Field;/** * @author shusheng * @description 通过反射获取成员变量并使用 * @Email shusheng@yiji.com * @date 2019/1/5 16:37 */public class ReflectDemo2 { public static void main(String[] args) throws Exception { // 获取字节码文件对象 Class c = Class.forName("com.yjf.esupplier.common.test.Person"); // 只能获取公共的成员变量 Field[] fields1 = c.getFields(); for (Field field : fields1) { System.out.println(field); } System.out.println("-----------------------------------------"); // 获取所有的成员变量 Field[] fields2 = c.getDeclaredFields(); for (Field field : fields2) { System.out.println(field); } // 通过无参构造方法创建对象 Constructor con = c.getConstructor(); Object obj = con.newInstance(); System.out.println(obj); // 获取单个的成员变量 // 获取address并对其赋值 Field addressField = c.getField("address"); // 给obj对象的addressField 字段设置值为"北京" addressField.set(obj, "北京"); System.out.println(obj); // 获取name并对其赋值 Field nameField = c.getDeclaredField("name"); nameField.setAccessible(true); nameField.set(obj, "林青霞"); System.out.println(obj); // 获取age并对其赋值 Field ageField = c.getDeclaredField("age"); ageField.setAccessible(true); ageField.set(obj, 27); System.out.println(obj); }}
package com.yjf.esupplier.common.test;/** * @author shusheng * @description * @Email shusheng@yiji.com * @date 2018/12/29 13:42 */public class Person { private String name; int age; public String address; public Person() { } private Person(String name) { this.name = name; } Person(String name, int age) { this.name = name; this.age = age; } public Person(String name, int age, String address) { this.name = name; this.age = age; this.address = address; } public void show() { System.out.println("show方法的输出"); } public void method(String s) { System.out.println("method方法的输出: " + s); } public String getString(String s, int i) { return s + "---" + i; } private void function() { System.out.println("function方法的输出"); } @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", address=" + address + "]"; }}