Dynamically create classes in Java

I would like to create a class in Java based on the fields defined in the XML configuration file:

For example: if the XML file contains (syntax has been cracked for publication):

<property name="agent_host"></property> <property name="subsystem"></property> 

then inside he will create a class event, such as Event (String agentHost, String subSystem), which the client can create. Note: the client always knows that this class will be called "Event", but does not know how many "required parameters" it needs to pass.

On the other hand, if I have an XML file with:

 <property name="agent_host"></property> 

then it will create an event (String eventHost) that the client can use to create the instance.

+2
source share
4 answers

Yes, you could use reflection, but what comes to my mind works with a class that you can add to a property. Imagine a class that has one encapsulated HashMap using String as the key (for the attribute name) and attribute value so that you can read the XML file, and for the evey property, add the attribute to a similar class. For this line:

 <property name="subsystem" type="String">value123</property> GenericClass c = new GenericClass(); c.addAttribute("subsystem", new String("value123")); //and you could implement a get and set methods like this: public String getAttributeValue(String attributeName) { return internalHashMap.get(attributeName).toString(); } 

Using this, you can also implement setAttributeValue will be pretty simple, I think

+2
source

This is not the class you want, this is data. Why not use a hash map? I really dislike the Bean style classes - they encourage poor coding (there is no room in the generated class for the actual code, so everything is ultimately driven by external code).

You can simply load the hash map from your XML and paste it into the real object - this way you do not have to worry about the actual passage of the hash, you transfer the real object with real business methods and real type of security - just HAPPENS uses an internal hashmap to store data instead of member variables.

I did a lot more than that, but at some point you realize that Hibernate does everything you want for you.

+1
source

I think DynaBean from Commons-BeanUtils might be what you are looking for.

DynaBean is a Java object that supports properties whose names, data types, and values ​​can be dynamically changed. To the extent possible, the other components of the BeanUtils package recognize these beans and treat them as standard JavaBeans for retrieving and setting property values.

+1
source

If you are really interested in creating a class dynamically, try Bash extension libraries such as BCEL from Apache.

+1
source

Source: https://habr.com/ru/post/1438484/


All Articles