jeudi 19 septembre 2019

Trying to change the value of a property at runtime using reflection results in NullPointerException

I have a class that I'm writing unit tests for:

import java.io.File;

public class MyLogger {

    private final File logFile = new File("default");

    public File getLogFile() {
        return this.logFile;
    }
}

I would like to change the value assigned to logFile from within another class, e.g:

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class Main {

    public static void main(String[] args) throws NoSuchFieldException, SecurityException, Exception {

        MyLogger logger = new MyLogger();
        System.out.println(logger.getLogFile());

        setFinal(MyLogger.class.getDeclaredField("logFile"), new File("changed"));
        System.out.println(logger.getLogFile());
    }

    private static void setFinal(Field field, Object newValue) throws Exception {
        field.setAccessible(true);

        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

        field.set(null, newValue);
    }
}

But I'm getting the output/exception below:

default
Exception in thread "main" java.lang.NullPointerException
    at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:57)
    at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:75)
    at java.lang.reflect.Field.set(Field.java:764)
    at Main.setFinal(Main.java:23)
    at Main.main(Main.java:12)





Aucun commentaire:

Enregistrer un commentaire