使用反射比较字段值 [英] Comparing field values using reflection

查看:94
本文介绍了使用反射比较字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图以通用方式比较两个不同对象的字段值。我有一个函数(如下所示),它接收两个对象,然后获取字段,然后比较循环中的字段,如果它们不相同,则将字段添加到列表中 - 这是正确的方法吗?

I am trying to compare the field values of two different objects in a generic way. I have a function (seen below) that takes in two Objects and then gets the fields and then compares the fields in a loop and adds the fields to a list if they are not the same - is this the proper way to do this?

public void compareFields(Object qa, Object qa4) throws FieldsNotEqualException
{

  Field[] qaFields = qa.getClass().getFields();
  Field[] qa4Fields = qa4.getClass().getFields();

  for(Field f:qaFields) 
  { 

    for(Field f4:qa4Fields)
    {
       if(f4.equals(f))
       {
           found = true;
           break;
       }
       else
       {
           continue;
       }
    }
  }

 if(!found)
 {
    report.add(/*some_formatted_string*/) //some global list 
    throw new FieldsNotEqualException();
 }
}

我在谷歌搜索,我看到C#就像一个PropertyInfo类 - Java有类似的东西吗?
另外,有没有办法像 f.getFieldValue() - 我知道没有这样的方法,但也许有另一种方式??? / p>

I was googling and I saw that C# had like a PropertyInfo Class - does Java have anything like that? ALSO, is there a way to do like f.getFieldValue() -I know there is no method like this but maybe there is another way???

推荐答案

您可以查看org.apache.commons.lang.builder.EqualsBuilder,这将为您节省很多麻烦,如果你我想通过现场比较做一个领域。

You might check out org.apache.commons.lang.builder.EqualsBuilder which will save you a lot of this hassle if you're wanting to do a field by field comparison.

org.apache.commons.lang.builder.EqualsBuilder.reflectionEquals(Object, Object)

如果您想自己比较字段,请查看 java.lang.Class.getDeclaredFields()这将为您提供包括非公共字段在内的所有字段。

If you're wanting to compare fields yourself, check out java.lang.Class.getDeclaredFields() which will give you all the fields including non-public fields.

要比较字段的值,请使用 f.get(qa).equals(f.get(qa4))目前,您实际上是在比较字段实例而不是值。

To compare the value of the fields use f.get(qa).equals(f.get(qa4)) Currently, you are actually comparing the field instances and not the values.

这篇关于使用反射比较字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆