package com.yjf.esupplier.common.test; /** * @author shusheng * @description 调用反射工具类 * @Email shusheng@yiji.com * @date 2019/1/5 18:37 */ public class ReflectDemo6 { public static void main(String[] args) throws Exception { Person p = new Person(); ReflectTool t = new ReflectTool(); t.setProperty(p, "name", "林青霞"); t.setProperty(p, "age", 27); t.setProperty(p, "address", "这是一个地址"); System.out.println(p); System.out.println("----------------------------"); } }
package com.yjf.esupplier.common.test; import java.lang.reflect.Field; /** * @author shusheng * @description * @Email shusheng@yiji.com * @date 2019/1/5 19:21 */ public class ReflectTool { public void setProperty(Object obj, String propertyName, Object value) throws Exception { // 根据对象获取字节码文件对象 Class c = obj.getClass(); // 获取该对象的propertyName成员变量 Field field = c.getDeclaredField(propertyName); // 取消访问检查 field.setAccessible(true); // 给对象的成员变量赋值为指定的值 field.set(obj, value); } }
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 + "]"; } }