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();
}
如何为这些类对象添加值。
答案 0 :(得分:2)
cglib的BeanGenerator
不仅生成动态类,还添加了访问器方法。那么如何做一个像这样的反射方法调用:
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。
可能有更有效的方法,可能只是为了向您展示这个概念。