简体   繁体   English

如何从 Java 中的外部源(例如文件)自动读取 object 属性?

[英]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.我想知道是否有某种方法可以让我从某个源文件或 map 自动更新 object 属性。

To elaborate, suppose I have an object with properties x, y, width, height of type Float .详细地说,假设我有一个 object ,其属性x, y, width, height类型为Float And I have a map with key-value pair for the properties in the form <String, Float> .我有一个 map ,其属性的键值对格式为<String, Float> To update the properties of the object, I would iterate over the map and do something like:要更新 object 的属性,我将遍历 map 并执行以下操作:

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.如果我向 class 添加更多属性,我将不得不继续添加这样的代码。 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.如果每个 class 属性都映射到一个属性,那么您可以获得所有 class 属性并正确迭代它们以更新属性值。 That way you don't need to keep adding if clauses.这样你就不需要继续添加 if 子句了。

Does it help?它有帮助吗?

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

Populate the JavaBeans properties of the specified bean, based on the specified name/value pairs.根据指定的名称/值对填充指定 bean 的 JavaBeans 属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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