开发者

add property for a object dynamicly

开发者 https://www.devze.com 2023-01-27 14:37 出处:网络
Hi: In our application,we have retrive some data from the database,for example,the table have columes: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.

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 Cl开发者_如何学Pythonass?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消