Kulasangar
Kulasangar

Reputation: 9444

How to dynamically generate a Java Bean class using plain Java?

I went through some of the samples that have used libraries to generate bean classes from JSON, XML etc. What I would like to know is, whether there's a way to dynamically generate a java bean class, with the parameters I give?

For example if I give an array of Strings as arguments which would represent the properties of the Pojo class for now, how can I generate the POJO?

Arguments: {"field1", "field2", "field3"}

Generate POJO would be:

public class TestBean { 
    private String field1; 

    TestBean() {
    }

    public String getField1() { 
      return field1; 
    } 

    public void setField1(String field1) { 
      this.field1 = field1; 
    }    
}

It should be the same for field2 and field3 as well.

Here I'm assuming that all the properties above are String and the class name is constant for now. Is there any way I can achieve this? Thanks in advance.

Upvotes: 1

Views: 1484

Answers (1)

rghome
rghome

Reputation: 8841

The problem with generating an actual Java class at runtime is that there is no way you can access it using standard Java syntax as the compiler doesn't know about it.

In practice therefore, most people just use a map in this circumstance. The only case I can think where you would need to generate a real class is where there is some other code you can't change that requires a Java object and inspects it dynamically using reflection or otherwise.

If you don't need this you are better off using a map, or possibly some utility class designed to emulate a Java Bean.

The Apache BeanUtils package provides the DynaBean interface to implement dynamic Java Beans. That said, the classes are only recognised as beans if accessed from the rest of the BeanUtils package.

There are several subclasses depending on what you want, for example, LazyDynaBean:

DynaBean myBean = new LazyDynaBean();
myBean.set("myProperty", "myValue");

Upvotes: 2

Related Questions