简体   繁体   English

从两个不同的类中获取相同的字段

[英]obtain same fields from two different classes

I have Class A and Class B 我有A级和B级

In Class AI have some fields 在类AI中有一些字段

private String name;
private String address;
private String phoneNo;

Class BI have some fields too BI类也有一些字段

private String name;
private String city;
private String phoneNo;

In my main Class I get fields from both classes 在我的主要课程中,我从两个课程中获取字段

A a = new A();
B b = new B(); 
Field[] fieldsFromA = a.getClass().getDeclaredFields();
Field[] fieldsFromB = b.getClass().getDeclaredFields();

I would like to have another Field[ ] where I can store fields that both exists in Class A and B 我想有另一个Field [],我可以存储A类和B类存在的字段

in ths example it would be name and phoneNo 在这个例子中,它将是名字和phoneNo

is there a simple way to do that ? 有一个简单的方法吗?

I was thinking of doing a double for loop to filter out the same fields and then add them into the array but there are cases that Class A may contain more fields than Class B or vise versa which may lead me to miss out some... 我想做一个双循环来过滤掉相同的字段,然后将它们添加到数组中,但有些情况下,A类可能包含比B类更多的字段,反之亦然,这可能会导致我错过一些...

We create two variables: 我们创建了两个变量:

A a = new A("name", "adress", "phoneNo");
B b = new B("name", "city", "phoneNo");

And get their fields: 得到他们的领域:

Field[] aF = a.getClass().getFields();
Field[] bF = b.getClass().getFields();

Then: 然后:

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);
});

The code above will put the names of the fields, which will be unique, into sets. 上面的代码会将字段的名称 (将是唯一的)放入集合中。

s1.retainAll(s2);

Here we get the intersection of the sets. 在这里,我们得到集合的交集。

String[] result = s1.toArray(new String[s1.size()]);
for (String f : result) {
    System.out.println(f);
}

and then we print the output. 然后我们打印输出。

You can convert this to a Set and then add it a third Set. 您可以将其转换为Set,然后将其添加到第三个Set。

Something like this you can do: 您可以这样做:

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

you can use a HashSet , and put all fields in class A into set 您可以使用HashSet ,并将A类中的所有字段放入set
then : as for fields in class B if it's contained in set then add it into your target array. 然后 :对于B类中的字段,如果它包含在set中,则将其添加到目标数组中。


the pseudocode 伪代码

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM