jeudi 8 février 2018

Changing the value of final static member of a nested static class [duplicate]

This question already has an answer here:

When I try to change the value of a static final member of a nested static class I don't see it working. When I try the below code to change the static final member of some other class it works.

   public class FinalPivateStaticMember {

        public static void main(String[] args) {
            System.out.println("Initial value == "+Test.val);
            try {
                Class cls = Class.forName("com.reflection.FinalPivateStaticMember$Test");
                try {
                    Field file_systems_loaded = cls.getDeclaredField("val");
                    file_systems_loaded.setAccessible(true);

                    Field modifiers = Field.class.getDeclaredField("modifiers");
                    modifiers.setAccessible(true);
                    try {
                        System.out.println("--"+file_systems_loaded.getModifiers());
                        modifiers.setInt(file_systems_loaded,file_systems_loaded.getModifiers() & ~Modifier.FINAL);
                        System.out.println("--"+file_systems_loaded.getModifiers());
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                    try {
                        file_systems_loaded.setBoolean(null,false);
                    } catch (IllegalAccessException e) {
                            e.printStackTrace();
                    }
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
            } catch (ClassNotFoundException e) {
                    e.printStackTrace();
            }
            System.out.print("Final value == "+Test.val);

        }

        static class Test{

           private  static final  boolean val = true;
        }

    }

Output of above code

Initial value == true
--26
--10
Final value == true





Aucun commentaire:

Enregistrer un commentaire