lundi 3 avril 2017

Java reflection set throwing NullPointerException with final non-static field

Following is a code snippet that I am using:

Logger logger = mock(Logger.class);
Field loggerField = MyChildClass.class.getSuperclass().getDeclaredField("logger");
loggerField.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(loggerField, loggerField.getModifiers() & ~Modifier.FINAL);
loggerField.set(null, logger);

The last line throws a NullPointerException. After looking further into it I noticed that the field that I am trying to reflect is a final non-static field as a result of which this error is being thrown.

I want to know what should I put in place of null in loggerField.set(null, logger);.

logger is defined in a parent class called MyOldParentClass as

protected final Logger logger = getLogger(getClass());





Aucun commentaire:

Enregistrer un commentaire