vendredi 16 juillet 2021

IllegalAccessException when trying to modify private static field

I tried to follow this Change private static final field using Java reflection

But for some reason i get java.lang.IllegalAccessException: Can not set static final java.lang.Long field DataRepositoryTests.Item.id to java.lang.Integer

for (Field field : Table.getDeclaredFields()){

                    System.out.println(Table.getSimpleName()); //prints "Item"
                    
                    field.setAccessible(true);

                    if (field.getName().equals(GeneratedValueFields.get(i).getName())) { 

                        System.out.println(field.getName()); //prints "id"

                        Field modifiersField = Table.getDeclaredField(GeneratedValueFields.get(i).getName()); 

                        System.out.println(modifiersField.getName()); //prints "id" as expected

                        modifiersField.setAccessible(true);
                        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); //error here

                        //data = 9 (Long)

                        field.set(null,data);


                    };

Now if i remove the line modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

I get java.lang.IllegalAccessException: Can not set static final java.lang.Long field DataRepositoryTests.Item.id to java.lang.Long

If i change the field to just private final and specify a Object

field.set(TableModel,data);

It works properly





Aucun commentaire:

Enregistrer un commentaire