【发布时间】:2018-08-07 07:24:37
【问题描述】:
假设我有 2 个课程:
public class Person
{
private String name;
private int age;
private Contact contact;
//getter & setter
}
public class Contact
{
private String phone;
private String email;
//getter & setter
}
使用上面的类,我想创建 2 个 Person 类的实例,具有不同的字段值。然后我想将 2 个对象的某些字段与它们的 getter 函数进行比较,但我不想比较所有字段。
例如,我想比较字段name 和phone,然后我会将这两个getter 方法存储到如下列表中:
List<WhatShouldBeTheDataType> funcList = new ArrayList<>();
funcList.add(MyClass::getName);
funcList.add(MyClass::getContact::getPhone) //I know this won't work, what should be the solution?
然后循环通过funcList,将我要比较的2个对象传递给函数,如果值不一样,将一些东西写入数据库。这可以用普通的if...else... 方式轻松完成,但是用Java 8 方式可以做到吗?
以下是我想以if...else... 方式实现的目标:
if(person1.getName() != person2.getName())
{
//message format basically is: "fieldName + value of object 1 + value of object 2"
log.append("Name is different: " + person1.getName() + ", " + person2.getName());
}
if(person1.getContact.getPhone() != person2.getContact().getPhone())
{
log.append("Phone is different: " + person1.getContact.getPhone() + ", " + person2.getContact.getPhone());
}
//other if to compare other fields
【问题讨论】: