简体   繁体   中英

How can I automate the reading of object properties from external sources (such as a file) in Java?

I was wondering if there's some way which allows me to automate the updating of object properties from some source as a file or a map.

To elaborate, suppose I have an object with properties x, y, width, height of type Float . And I have a map with key-value pair for the properties in the form <String, Float> . To update the properties of the object, I would iterate over the map and do something like:

if (key.equals("x")) x = (Float) map.get(key);
else if(key.equals("y")) y = (Float) map.get(key);
else if(key.equals("width")) width = (Float) map.get(key);
else if(key.equals("height")) height = (Float) map.get(key);

If I add more properties to the class, I'll have to keep adding code like this. So my question basically is, is there a way to automate this process so that it'll be easy to add new properties and update them as above? Possibly by the use of annotations?

Thanks, stormweaver

I would do that using reflection ( check out this link ). If every class attribute is mapped to a property, then you could get all class attributes and iterate over them properly to update the property values. That way you don't need to keep adding if clauses.

Does it help?

BeanUtils.populate(this, map) from commons-beanutils :

Populate the JavaBeans properties of the specified bean, based on the specified name/value pairs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM