假设我有一个班级Item
。项目具有对象属性和其他对象属性的集合:
public class Item
{
//Object attributes
String name;
int id;
Color color;
//Collection of object attributes
List<Parts> parts;
Map<int,Owner> ownersById;
}
我有一个相当简单的Web应用程序,允许对这些项目进行crud操作。这被分成单独的操作:
由于服务器负载过高,我在应用程序中实现了一个缓存,其中包含“最近使用的项目对象”及其简单属性和集合属性。
每当对项目名称进行编辑时,我都要执行以下操作:
为此,我创建了以下方法:
public void updateItem(Item itemWithoutCollectionData)
{
WebServiceInvoker.updateItemService(itemWithoutCollectionData)
Item cachedItemWithCollectionData = cache.getItemById(itemWithoutCollectionData.getId());
cachedItemWithCollectionData.setName(itemWithoutCollectionData.getName());
cachedItemWithCollectionData.setColor(itemWithoutCollectionData.getColor());
}
这种方法非常烦人,因为我必须逐个复制属性,因为我事先无法知道用户刚刚更新了哪些属性。出现错误是因为对象在一个地方发生了变化,但在这段代码中没有变化。我也不能只执行以下操作:cachedItem = itemWithoutCollectionData;
因为这会使我丢失itemWithoutCollectionData变量中不存在的集合信息。
有没有办法:
类:
public class BaseItem
{
String name;
int id;
}
public class ColoredItem
{
Color color;
}
答案 0 :(得分:0)
有许多事情可以用来增强你现有的东西,但我会指出两件可以帮助你解决问题的事情。
首先,我假设public void updateItem
是生产代码中的简化版本。所以;确保此方法是线程安全的,因为它在缓存方面是一个常见的来源。
其次,你提到了
也许通过反思,迭代所有非集合 类中的属性,因此以它的方式编写代码 如果在Item类中添加或删除未来字段,则无关紧要。
如果我正确理解了问题;那么,你可以使用BeanUtils.copyProperties()轻松实现这一点,这里有一个例子: http://www.mkyong.com/java/how-to-use-reflection-to-copy-properties-from-pojo-to-other-java-beans/
我希望它有所帮助。 欢呼声,