Java反射一 动态修改类的属性
Person.java
Mymain.javapackage fanshe;import java.lang.reflect.Field;import java.lang.reflect.Method;public class Mymain {public static void main(String[] args) throws Exception{Mymain.ceratePerson("fanshe.Person", "name", "Peter", "age", 30, "info");}private static void ceratePerson(String className, String namefield, String namevalue, String agefield, int agevalue, String methodname) throws Exception{Class clazz = Class.forName(className);Object o = clazz.newInstance();Field field_name = clazz.getDeclaredField(namefield);field_name.setAccessible(true);field_name.set(o, namevalue);Field field_age = clazz.getDeclaredField(agefield);field_age.setAccessible(true);field_age.setInt(o, agevalue);Method method = clazz.getDeclaredMethod(methodname);method.setAccessible(true);String result = (String)method.invoke(o);System.out.println(result);}}
运行结果:
My name is Peter, I'm 30 years old.