我想知道是否有某种方法可以让我自动更新来自某个源(例如文件或地图)的对象属性。
详细来说,假设我有一个具有 Float
类型属性 x、y、width、height
的对象。我有一个带有
形式的属性键值对的映射。要更新对象的属性,我将迭代映射并执行以下操作:
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);
如果我向类添加更多属性,我将不得不继续添加这样的代码。所以我的问题基本上是,有没有一种方法可以自动化此过程,以便可以轻松添加新属性并按上述方式更新它们?可能通过使用注释?
谢谢,
风暴编织者
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
发布评论
评论(2)
我会使用反射来做到这一点(查看此链接)。如果每个类属性都映射到一个属性,那么您可以获取所有类属性并正确迭代它们以更新属性值。这样你就不需要不断添加 if 子句。
有帮助吗?
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)
rel =“nofollow”>commons-beanutils:BeanUtils.populate(this, map)
from commons-beanutils: