2

If I have following Java code:

package a.b.c;
public class A{
  static class B{
     public B(){
     }
  }
}

I want to change class B's modifier to "public" at run-time via reflection, how can I do that? Thanks.

So the after effect will be like following:

package a.b.c;
public class A{
  public static class B{
     public B(){
     }
  }
}
copy
  • 21
  • 3
  • 1
    This will help you http://stackoverflow.com/questions/3301635/change-private-static-final-field-using-java-reflection – Runcorn Aug 05 '14 at 09:25
  • @Runcorn If I follow the link and try to modify the inner class modifier, I got following error: java.lang.IllegalArgumentException: Can not set int field java.lang.reflect.Field.modifiers to java.lang.Class – copy Aug 06 '14 at 01:24
  • The link applies to fields only. Not useable for types. – Cfx Jul 26 '16 at 15:01

1 Answers1

0

With reflection you cannot change the class modifiers but you can create objects of the specified class and invoke its methods.

You can get instance the class from the enclosing class with the method getDeclaredClasses(), and then modify the contructor and instantiate the object:

        Class a = A.class;
            Class subs[] = a.getDeclaredClasses();
            Object o = null;
            for (Class cls: subs) {
                if(cls.getCanonicalName().equals("A.B")){
                    for (Constructor ct: cls.getDeclaredConstructors()) {
                        ct.setAccessible(true);
                        o = ct.newInstance(new Inner());
                        // o is an instance of B
                        // you can get public and private method and invoke them
                        for (Method m: o.getClass().getDeclaredMethods())
                            if(m.getName().equals("....")){
                                m.setAccessible(true);
                                m.invoke(o, ....));
                                
                            }
                    }
                }
            }

Instead of the for loop you could get methods by name and list of parameters.