想問有方法更快對比2個objects中名字一樣attributes? 而2個object也有名字不一樣的attributes 但可以不用compare.
For example,
if (a.element1.equals(b.element1))
if (a.element2.equals(b.element2))
簡單以Field做驗證, 看看是不是你要的? 不過是簡單寫的, 要用的話結構可能要改改會比較好 ww
public class CheckTest{
@Test
public void checkTest1(){
A a = new A();
B b = new B();
var result = Arrays.stream(a.getClass().getDeclaredFields())
.filter( field -> !field.getName().contains("this$") )
.filter( fieldA ->
Arrays.stream(b.getClass().getDeclaredFields())
.anyMatch( fieldB->
fieldB.getName().equals(fieldA.getName())))
.peek( fieldA -> {
try {
System.out.println("Check for: " + fieldA.getName()+":" + fieldA.get(a));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
})
.allMatch( fieldA ->
Arrays.stream(b.getClass().getDeclaredFields())
.anyMatch( fieldB->
{
try {
return fieldB.get(b).equals(fieldA.get(a));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return true;
}
));
System.out.println("final result:" + result);
}
class A{
int a = 10;
String b = "ABC";
String c = "CDF";
}
class B{
int a = 10;
String b = "ABC";
String d = "CDF";
}
}
output:
Check for: a:10
Check for: b:ABC
final result:true
用JSONUtil把ojbect serialize成json string
String jsonString = JSONUtil.serialize(your_object);
再用正則表達式,把atttribute name全部抓出來放在listMatches陣列裡
List<String> listMatches = new ArrayList<String>();
Pattern pattern = Pattern.compile("\"([^\"]+)\":");
Matcher matcher = pattern.matcher(jsonString);
while( matcher.find() ) {
listMatches.add( matcher.group() );
}
..兩個object都抓
再用for去比對兩個listMatches裡,是否具有相同的attributes,有就println出來
for(String strA : listMachers1){
for(String strB : listMachers2){
if(strA==strB){
System.out.println(strA);
}
}
}
PS...我沒在寫java,只是用其他語言的邏輯來處理相同的事情,高手還請鞭小力一點,我怕痛