mercredi 22 juillet 2020

Exception is thrown when i try to call a reflection method

I am new to java and trying to use Java reflection to set value to static final field I found below example code and trying to compile in JAVA 11.

static void setFinalStatic(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 below Exception is thrown in Java 11 . Field class has a field called "modifiers" Could not figure out what is the issue here . It works for ArrayList , Set etc .

 Time elapsed: 2.383 s  <<< FAILURE!

java.lang.NoSuchFieldException: modifiers
        at java.base/java.lang.Class.getDeclaredField(Class.java:2412)




Aucun commentaire:

Enregistrer un commentaire