1

Given classes:

public class A {
    private UUID uuid;

    public A(){
         uuid = UUID.randomUUID();
    }
    // equals
}

class B extends A {
    private int b;
    // getters, setters, equals (invokes super.equals(...))
}

class Sample {

    public static void main(String[] args){
    B b1 = new B();   // 
    B b2 = B.class.newInstance();

    // now I want to take value of A.uuid from b1 and set it to b2
    }
}

Problem

I don't know how to get value of uuid field from b1 instance and set it to b2. Private fields in A class are unaccessible by B.class.getDeclaredFields() and similar methods... Does java compiler creates any synthetic accessors or smth like this?

NOTE

There are no public getters and setters in A class.

Why I want to do this?

I was facing with copying and pasting equals and hashCode methods tests, so I decided to write POJO methods testing framework pojo-tester It tests objects equality, hashcodes, getters, setters, toString and constructors, so you don't have to write tests by hand.

The problem is, that this library creates objects (new instances of class) by newInstance() method. After that I want to make them equal - all values of fields from base objects, should be set in newly created objects.

As you can guess, there is problem when equals method implementation depends on super.equals(...) and fields from super class have random values (like UUID) or are not public.

Is there any way to achieve this? Maybe some other library?

BTW

If someone knows how to do this and want to contribute, just send PR! :)

https://github.com/sta-szek/pojo-tester

Thanks

staszek
  • 251
  • 2
  • 9
  • 1
    See http://stackoverflow.com/questions/7966466/getting-first-parents-fields-via-reflection?rq=1 – Rob Nov 18 '16 at 19:00
  • And http://stackoverflow.com/questions/10638826/java-reflection-impact-of-setaccessibletrue?rq=1 – Rob Nov 18 '16 at 19:00
  • And http://stackoverflow.com/questions/1196192/how-do-i-read-a-private-field-in-java?rq=1 – Rob Nov 18 '16 at 19:01
  • ohh... That was so easy! Thanks you very much @Rob ! I have spent few hours on this and I do not know why I did not use the goodness of the `Field` object :) – staszek Nov 18 '16 at 21:27

1 Answers1

1

use this.

Field[] fs = b.getClass().getSupperClass().getDeclaredFields();
for(Field f: fs)
 {
  if(f.getName().equals("uuid"))
     {
       f.setAccessible(true);
       return f.get( new UUID() );
      }
 }
Ali Bagheri
  • 3,068
  • 27
  • 28
  • shouldn't `f.get( new UUID() );` be `f.get(b);`? But yeah I think the missing link was `setAccessible(true)` – RobCo Apr 09 '17 at 09:22