通用算法生成的字段的差异两豆?字段、算法、差异

由网友(喜喜)分享简介:让我们假设你有一个bean类的两个实例,你想显示什么在两个实例之间变化的总结 - 例如,你有一个bean重新$ P $在psenting用户的设置您的应用程序,并且希望能够显示什么样的新设置的用户提交改变列表(例如#1)对已存储的用户(例如#2)。Let's say you have two instances of...

让我们假设你有一个bean类的两个实例,你想显示什么在两个实例之间变化的总结 - 例如,你有一个bean重新$ P $在psenting用户的设置您的应用程序,并且希望能够显示什么样的新设置的用户提交改变列表(例如#1)对已存储的用户(例如#2)。

Let's say you have two instances of the same bean type, and you'd like to display a summary of what has changed between the two instances - for example, you have a bean representing a user's settings in your application, and you'd like to be able to display a list of what has changed in the new settings the user is submitting (instance #1) versus what is stored already for the user (instance #2).

是否有一个常用算法或设计图案为任务如此,或许一些可以被抽象和重新用于不同类型的咖啡豆? (我有一个好名字很难思考对这类问题知道该怎么谷歌的)。我检查公地的beanutils并没有什么突然出现了我。

Is there a commonly used algorithm or design pattern for a task such as this, perhaps something that can be abstracted and re-used for different types of beans? (I'm having a hard time thinking of a good name for this type of problem to know what to Google on). I've checked commons-beanutils and nothing popped out at me.

推荐答案

如果你在谈论的比较值,我会考虑使用反射,只是通过现场比较它们领域。

If you are talking about comparing values, I would consider using reflection and just comparing them field by field.

事情是这样的:


    Field[] oldFields = oldInstance.class.getDeclaredFields();
    Field[] newFields = newInstance.class.getDeclaredFields();
    StringBuilder changes = new StringBuilder();

    Arrays.sort(oldFields);
    Arrays.sort(newFields);

    int i = 0;
    for(Field f : oldFields)
    {
       if(!f.equals(newFields[i]))
       {
          changes.append(f.getName()).append(" has changed.n");
       }
       i++;
    }

这code尚未经过测试。您可能需要获得在字段中的值,比较只是比较区域彼此之间的他们,而不是,但它应该工作在理论上。

This code hasn't been tested. You might need to get the values in the fields and compare them instead of just comparing fields to each other, but it should work in theory.

阅读全文

相关推荐

最新文章