Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change a private field in a parent class

I have using the Vaadin framework and want to override some behavior.

Problem is that all setters for a field have side effects that I don't want to invoke.

For this reason I want to set the private field directly.

Here's my code:

@Override
public void setItemDataSource(Item itemDataSource) {
    //do some stuff
    java.lang.reflect.Field privateField = this.getClass().getDeclaredField(itemDatasource); //Yes the spelling is correct.
    privateField.set(this, itemDataSource);   <<-- I get an error.
    //do more stuff

I get the following error.

//TODO: copy paste error.

Apparently I'm not supposed to include this as the object who's field need to be changed, but some other reference.
What am I doing wrong?

like image 772
Johan Avatar asked Jan 14 '23 00:01

Johan


1 Answers

You need to make it accessible first:

privateField.setAccessible(true);
privateField.set(this, itemDataSource);
like image 140
assylias Avatar answered Jan 19 '23 10:01

assylias