使用beanutils创建DynamicBean
import java.lang.reflect.InvocationTargetException;import org.apache.commons.beanutils.BasicDynaBean;import org.apache.commons.beanutils.BasicDynaClass;import org.apache.commons.beanutils.DynaBean;import org.apache.commons.beanutils.DynaProperty;import org.apache.commons.beanutils.PropertyUtils;public class Test{ public static void main(String[] args) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException { test(); } private static void test() throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException { DynaProperty[] dynaProperties = new DynaProperty[] { new DynaProperty("name", String.class), new DynaProperty("age", Integer.class) }; BasicDynaClass basicDynaClass = new BasicDynaClass("person", BasicDynaBean.class, dynaProperties); DynaBean personBean = basicDynaClass.newInstance(); personBean.set("name", "zhangming"); personBean.set("age", 123); System.out.println("-----------"); System.out.println(personBean.get("name")); System.out.println(personBean.get("age")); System.out.println("......"); System.out.println(PropertyUtils.getSimpleProperty(personBean, "name")); }}
?