vendredi 18 novembre 2016

Java reflection, change value of field declared in superclass

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! :)

http://ift.tt/2go0fWa

Thanks





Aucun commentaire:

Enregistrer un commentaire