Creating dynamic POJOs and set values to it

拜拜、爱过 提交于 2020-01-03 04:01:07

问题


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();
}

How will I add values to these class object.


回答1:


cglib's BeanGenerator not only generates a dynamic class, it also adds accessor methods. So how about doing a reflective method call like this:

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");

Your bean is now (partially) populated.

There might be more efficient ways, probably, this is just to show you the concept.



来源:https://stackoverflow.com/questions/15653770/creating-dynamic-pojos-and-set-values-to-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!