Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
701 views
in Technique[技术] by (71.8m points)

class - Dynamically create classes in Java

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

For example: if the XML file contains (the syntax has been maligned for posting):

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

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

On the other hand if I have a XML file with:

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

then it will create Event(String eventHost) that the client can use for instantiation.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, you could use reflection, but what comes to my mind is working with a class that you could add property. Imagine a class that has one encapsulated HashMap using a String as a key (for the attribute name) and the value of the attribute so you could read the XML file and for evey property add the attribute to the class like. 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 could also implement a setAttributeValue will be quite simple I think


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...