比较两个不相关对象的字段 [英] Compare fields of two unrelated objects

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

问题描述

我有两个不同类的对象,它们共享一些具有相同名称和类型的字段。这两个对象彼此不相关。我无法创建接口或父类。

I've got two objects of different classes that share some fields with the same name and type. These two objects are not related to each other. There's no possibility for me to create an interface or a parent class.

现在,我想比较这些共享字段,据我所知,应该可以使用反射。

Now I want to compare those shared fields and as far as I know this should be possible using reflection.

这些是我为比较方法编写的步骤:

These are the steps I've written for such a compare method:

Field[] inputFields = input.getClass().getDeclaredFields();
for (Field field : inputFields ) {
    log.info(field.getName() + " : " + field.getType());
}

将有一个名为数据库的对象 inputFields 与哪个字段进行比较。

There will be an object called database to which's fields the inputFields are compared.

不幸的是,我不知道如何获取我的领域的价值。

Unfortunately I don't know how to get the value of my fields. Do you have some hints for me?

好,并带有 field.get(input)我现在有价值,但是也许我错了,那不是我所需要的。
实际上,我想将此字段与另一个字段进行比较,因此我需要在此字段上调用equals方法。但是首先,我必须将其转换为适当的课程。
那么是否有像((field.getClass())field).equals(...)这样的东西可以工作?

Ok, with field.get(input) I've got the value now, but maybe I was wrong and that's not what I need. Actually, I want to compare this field with another one, so I need to call the equals method on this field. But at first I've got to cast it to it's appropriate class. So is there something like ((field.getClass()) field).equals(...) that would work?

推荐答案

我认为您正在寻找 Field.get()

I think you're looking for Field.get():

for (Field field : inputFields ) {
    log.info(field.getName() + " : " 
             + field.getType() + " = " 
             + field.get(input);
}

这篇关于比较两个不相关对象的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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