使用反射比较字段值

编程入门 行业动态 更新时间:2024-10-24 18:22:05
本文介绍了使用反射比较字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.apachemons.lang.builder.EqualsBuilder,这将为您节省很多麻烦,如果你我想通过现场比较做一个领域。

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

org.apachemons.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.

更多推荐

使用反射比较字段值

本文发布于:2023-11-11 18:36:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1579248.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   反射

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!