Search code examples
javaclassdynamicpojo

Creating dynamic POJOs and set values to it


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.


Solution

  • 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.