How to change a private field in a parent class

java, private, reflection

Solution

You need to make it accessible first:

privateField.setAccessible(true);
privateField.set(this, itemDataSource);

Problem

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?

Original source