简体   繁体   English

通过反射将内部 Java 类修饰符更改为公共

[英]Change Inner Java Class Modifier to Public via Reflection

If I have following Java code:如果我有以下 Java 代码:

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?我想在运行时通过反射将 B 类的修饰符更改为“public”,我该怎么做? Thanks.谢谢。

So the after effect will be like following:所以之后的效果会是这样的:

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

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:您可以使用getDeclaredClasses()方法从封闭类中获取类的实例,然后修改构造函数并实例化对象:

        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.您可以通过名称和参数列表获取方法,而不是 for 循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM