动态添加对象的属性 [英] add property for a object dynamicly

查看:136
本文介绍了动态添加对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨:
在我们的应用程序中,我们从数据库中检索了一些数据,例如,表格中包含以下字符:id,name,age,address,email。

Hi: In our application,we have retrive some data from the database,for example,the table have columes:id,name,age,address,email.

然后我们将根据客户获得一些这些属性。

Then we will get some of these propertis according to the client.

如果客户需要id,name,我们得到id名称,如果客户需要id,name,age,我们得到id,name,age。

If client need the id, name, we get the id name, if client need id, name, age, we get the id, name, age.

现在我们要创建一个包装这些属性的类。但是我们并不确切地知道请求哪个字段。

Now we want to create a class to wrap these properties. However we do not know exactly which field are requested.

String[] requestPro={"name","id"}; //this field is specified by client
Map<String, Object> map=new HashMap<String, Object>();
Entity en=Entity.newInstance();
for(String p:requestPro){
    map.put(p, BeanUtils.getProperty(en, p));
}

我可以在这里用一个类替换地图吗?

Here can I replace the map with a Class?

推荐答案

如果我理解你正确,你想要动态地向类添加属性,或者更确切地说:向类的特定实例添加属性。

If I understand you right, you want to dynamically add properties to a class, or rather: to a specific instance of a class.

前者可能是例如在Groovy中,每个类都有一个元类对象,您可以在运行时为其分配行为,后者在JavaScript中是可能的,您可以在其中将行为分配给对象的原型和对象本身。但是这些版本都不可能在Java中使用,所以在Java中可以使用Map或类似的结构。

The former is possible e.g. in Groovy, where there is a metaclass object for every class, to which you can assign behavior at runtime, the latter is possible in JavaScript, where you can assign behavior both to an object's prototype and to an object itself. But neither of those versions is possible in Java, so using a Map or a similar structure is the thing to do in Java.

这篇关于动态添加对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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