Add a property to an object dynamically

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

Then we will get some of these properties according to customer.

If a client needs an identifier, name, we get an identifier, if you need a client identifier, name, age, we get an identifier, name, age.

Now we want to create a class to transfer these properties. However, we do not know exactly which field is being 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)); } 

Can I replace the card with a class here?

+4
source share
1 answer

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

The former is possible, for example, in Groovy, where for each class there is a metaclass object to which you can assign runtime behavior, the latter is possible in JavaScript, where you can assign behavior to both the prototype of the object and the object itself. But none of these versions is possible in Java, so using a map or similar structure is what you need to do in Java.

+2
source

All Articles