Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access private class members in Java?

I have data model classes that contain private fields which are meant to be read-only (via a getter function). These fields are set by my JPA persistence provider (eclipselink) during normal operation, using the contents of the database. For unit tests, I want to set them to fake values from a mockup of the persistence layer. How can I do that? How does eclipselink set these values, anyway?

Simplified example:

@Entity
class MyEntity
{
    @Id
    private Integer _ix;

    public Integer ixGet()
    {
        return this._ix;
    }
}
like image 671
Hanno Fietz Avatar asked Nov 27 '22 08:11

Hanno Fietz


2 Answers

Can you just Mock the Entity itself, providing your own implemenations of the getters?

You could create an anonymous extension in your mock persistence layer:

MyEntity x = new MyEntity() {
    public Integer ixGet() { return new Integer(88); }
};
like image 110
djna Avatar answered Dec 05 '22 16:12

djna


You need to use the Reflection API. Use Class.getField() to get the field, then call setAccessable(true) on that field so that you may write to it, even though it is private, and finally you may call set() on it to write a new value.

For example:

public class A {
    private int i;
}

You want to set the field 'i' to 3, even though it is private:

void forceSetInt(Object o, String fieldName, int value) {
    Class<?> clazz = o.getClass();
    Field field = clazz.getDeclaredField(fieldName);
    field.setAccessible(true);
    field.set(o, value);
}

There are a number of exceptions that you will need to handle.

like image 23
Jonathan Avatar answered Dec 05 '22 18:12

Jonathan