创建动态POJO并为其设置值

final Map<String, Class> properties = new HashMap<String, Class>(); properties.put("jobName", String.class); properties.put("companyName", String.class); properties.put("totalApplicantForJob", String.class); final Class beanClass = createBeanClass("ApplicantCountVsJobBoards", properties); public static Class createBeanClass (final String className, final Map<String, Class> properties) { final BeanGenerator beanGenerator = new BeanGenerator(); // NamingPolicy policy = //beanGenerator.setNamingPolicy(null); BeanGenerator.addProperties(beanGenerator, properties); return (Class) beanGenerator.createClass(); } 

我将如何向这些类对象添加值。

cglib的BeanGenerator不仅生成动态类,还添加了访问器方法。 那么如何做一个像这样的reflection方法调用:

 Object instance = beanClass.newInstance(); // Creates a new object of your dynamic class Method setJobName = beanClass.getMethod("setJobName", String.class); // Gets the setJobName method that takes one String argument method.invoke(instance, "Super Cool Job"); 

你的bean现在(部分)填充了。

可能会有更有效的方法,这可能只是为了向您展示这个概念。