在Java中动态创建类 [英] Dynamically create classes in Java

查看:212
本文介绍了在Java中动态创建类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据我的XML配置文件中定义的字段,在Java中创建一个类:


例如:如果XML文件包含(语法已被标记为发布):



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>

然后在内部它将创建一个类Event,如Event(String agentHost,String subSystem)可以实例化。注意:客户端总是知道这个类将被称为事件,但不知道它需要通过多少强制参数。

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.

另一方面,如果我有一个XML文件:

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

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

那么它将创建客户端可用于实例化的Event(String eventHost)。

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

推荐答案

是的,你可以使用反射,但是我想到的是使用一个类,你可以添加属性。
想象一个类,它有一个封装的HashMap,使用String作为键(属性名称)和属性的值,所以你可以读取XML文件,并为evey属性添加属性到类。
对于这一行:

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();
}

使用这个也可以实现setAttributeValue
会很简单我认为

Using this you could also implement a setAttributeValue will be quite simple I think

这篇关于在Java中动态创建类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆