[英]obtain same fields from two different classes
我有A級和B級
在類AI中有一些字段
private String name;
private String address;
private String phoneNo;
BI類也有一些字段
private String name;
private String city;
private String phoneNo;
在我的主要課程中,我從兩個課程中獲取字段
A a = new A();
B b = new B();
Field[] fieldsFromA = a.getClass().getDeclaredFields();
Field[] fieldsFromB = b.getClass().getDeclaredFields();
我想有另一個Field [],我可以存儲A類和B類存在的字段
在這個例子中,它將是名字和phoneNo
有一個簡單的方法嗎?
我想做一個雙循環來過濾掉相同的字段,然后將它們添加到數組中,但有些情況下,A類可能包含比B類更多的字段,反之亦然,這可能會導致我錯過一些...
我們創建了兩個變量:
A a = new A("name", "adress", "phoneNo");
B b = new B("name", "city", "phoneNo");
得到他們的領域:
Field[] aF = a.getClass().getFields();
Field[] bF = b.getClass().getFields();
然后:
Set<String> s1 = new HashSet<String>();
Set<String> s2 = new HashSet<String>();
List<Field> aFL = Arrays.asList(aF);
aFL.forEach(field -> {
String temp = field.getName();
s1.add(temp);
});
List<Field> bFL = Arrays.asList(bF);
bFL.forEach(field -> {
String temp = field.getName();
s2.add(temp);
});
上面的代碼會將字段的名稱 (將是唯一的)放入集合中。
s1.retainAll(s2);
在這里,我們得到集合的交集。
String[] result = s1.toArray(new String[s1.size()]);
for (String f : result) {
System.out.println(f);
}
然后我們打印輸出。
您可以將其轉換為Set,然后將其添加到第三個Set。
您可以這樣做:
Set<Field> mySet1 = new HashSet<Field>(Arrays.asList(fieldsFromA));
Set<Field> mySet2 = new HashSet<Field>(Arrays.asList(fieldsFromB));
mySet2.addAll(mySet1);
// then you can convert it Array
您可以使用HashSet
,並將A類中的所有字段放入set
然后 :對於B類中的字段,如果它包含在set中,則將其添加到目標數組中。
偽代碼
for(File file: A){
set.add(file);
}
for(File file: B){
if(set.contains(file)){
targetRes.add(file);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.