创建动态POJO并为其设置值 [英] Creating dynamic POJOs and set values to it
本文介绍了创建动态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();
}
如何将值添加到这些类对象中。
How will I add values to these class object.
推荐答案
cglib的 BeanGenerator
不仅生成一个动态类,还添加了访问器方法。那么如何做一个反射方法调用像这样:
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");
现在(部分)填充您的bean。
Your bean is now (partially) populated.
可能有更有效的方法,这可能只是为了向您展示这个概念。
There might be more efficient ways, probably, this is just to show you the concept.
这篇关于创建动态POJO并为其设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文