java 动态添加对象的属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4323328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 05:51:30  来源:igfitidea点击:

add property for a object dynamicly

javareflection

提问by hguser

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

您好:在我们的应用程序中,我们从数据库中检索了一些数据,例如,该表有列:id、name、age、address、email。

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

然后我们会根据客户得到一些这些属性。

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

如果客户端需要id、name,我们得到id name,如果client需要id、name、age,我们得到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?

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

采纳答案by Sean Patrick Floyd

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

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

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.

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