1

I have Class A and Class B

In Class A I have some fields

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

Class B I have some fields too

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

in ths example it would be name and 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...

securenova
  • 482
  • 1
  • 9
  • 25
  • 2
    Check `Arrays` class. There is some interesting methods to check if an element is in an array. But you should look to _How to compare to arrays_ first – AxelH Dec 14 '16 at 06:57
  • 2
    Possible duplicate of [Java Array, Finding Duplicates](http://stackoverflow.com/questions/3951547/java-array-finding-duplicates) – AxelH Dec 14 '16 at 06:58
  • Why not use an interface for the common properties? – Strelok Dec 14 '16 at 07:00
  • 1
    What you describe sounds like a bad design. Usually you should not use reflections as "normal day" tool. I do not know exactly what you want to do, but as long as you need to solve simple tasks, avoid the use of reflections. In case you are following a higher purpose I would recommend you to use annotations on fields that will be processed by your framework. Then you can scan for annotations reflectively and process the fields you've found. Using the convention like "fields must have the same name" is dangerous as it is not well documented and error prone. – UNIQUEorn Dec 14 '16 at 07:01
  • @UNIQUEorn What I'm trying do (for a start) is copy the same fields from a formbean to an entitybean , I don't want to keep setting each field from the formbean to the entitybean everytime... – securenova Dec 14 '16 at 07:14
  • The Possible duplicate question is finding duplicates in the same array , I have 2 arrays and their lengths are not the same , so I can't definitely put either one on the top layer for-loop...... – securenova Dec 14 '16 at 07:15
  • "I don't want to keep setting each field from the formbean to the entitybean everytime" And how did you hope to go about setting a private field in the entitybean ? – Erwin Smout Dec 14 '16 at 07:43
  • @ErwinSmout well I input data from my browser , I send a form to the backend, use spring to map the form with a formbean, I want to put some fields from the formbean to the entitybean so I can save it to a table in my database.The point is that these two beans have same fields, not all of them of course , I just want to copy the ones the same to the other, that's all , so I'm hoping to implement a method to do that , something similar to copyProperties method in spring but I have to customize it. Writing my own reflection implementation is another solution, just experimenting , that's all... – securenova Dec 14 '16 at 08:03
  • You will have to map the fields using their names as string. All those HashSet answers will not work as long as they work on the fields (different equals method). What you want to do will be more tricky if you have multiple classloaders at place. Then even field "A" from class A will not be equal to field "A" from class A loaded by another classloader which might be possible depending on your environment. I would strongly recommend you to redesign that part of your models because all these reflection stuff is dangerous and if it fails it will be the nastiest thing to debug! – UNIQUEorn Dec 14 '16 at 09:20
  • One more thing: Why do you separate your formbean and your entity bean. With a good design it is possible to get rid of this unneccessary separation. And in the worst case your formbean holds a reference to the entitybean and works on it, instead of implementing the same member variables. – UNIQUEorn Dec 14 '16 at 09:25
  • @UNIQUEorn , mapping fields using names is the next step , I know how to do that so I didn't ask that part ,thks. I agree that formbeans can be replaced with entitybeans, but I view my entitybean as a representation of my table in the database , my formbean as a representation of my input form from the browser , sometimes the two are not simply one to one alike , there are still differences, so I can't be sure if replacing formbeans is the best solution in every scenario, but I would like to know more, I will surely do more research on this, and reflection too. – securenova Dec 14 '16 at 10:33

3 Answers3

1

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.

ItamarG3
  • 4,092
  • 6
  • 31
  • 44
1

You can convert this to a Set and then add it a third 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
Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108
1

you can use a HashSet, and put all fields in class A into set
then: as for fields in class B if it's contained in set then add it into your target array.


the pseudocode

for(File file: A){
    set.add(file);
}
for(File file: B){
    if(set.contains(file)){
        targetRes.add(file);
    }
}
nail fei
  • 2,179
  • 3
  • 16
  • 36