简体   繁体   English

Java Reflection API。 如果不公开,则无法实例化内部类

[英]Java Reflection API. Cant instantiate Inner Class if its not public

Please help me in reflection api. 请帮助我反射API。 I cant instantiate inner class if it hasnt "public" modifier. 我无法实例化内部类,如果它没有“ public”修饰符。 I have classes: 我有课:

public abstract class AbstractClass {
  String str;
    public AbstractClass (String str) {
        this.str = str;
    }
  abstract void process(String str);
}

and

public class Outer {  

  class Inner extends AbstractClass{
    Inner(String str) {
        super(str);
    }

    @Override
    void process(String str) {
        //doSmth
    }
  }
}

And i have method in another place like this: 我在另一个地方有这样的方法:

void fillArray (AbstractClass innerAbstract) {
    try {
        ArrayList<AbstractClass> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Object outerClazz = Class.forName(innerAbstract.getClass().getEnclosingClass().getName()).newInstance();
            Class<?> innerReal = Class.forName(innerAbstract.getClass().getName());
            Constructor<?> ctor = innerReal.getConstructor(outerClazz.getClass(), String.class);
            AbstractClass resultClass = (AbstractClass) ctor.newInstance(outerClazz, innerReal.getName());
            list.add(resultClass);
            resultClass.process("STR");
        }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException |
            NoSuchMethodException | SecurityException | IllegalArgumentException |
            InvocationTargetException ex) {
        ex.printStackTrace();
    }

}

Inner class - is a realization of AbstractClass. 内部类-是AbstractClass的实现。 AbstractClass will have a lot of such realizations in different packages and classes. 在不同的包和类中,AbstractClass将具有许多这样的实现。

The question is. 问题是。 All it works fine, when inner classes have public modifier. 当内部类具有public修饰符时,一切正常。 But it must not be public. 但是它一定不能公开。 When inner classes have public modifier, i can get a list of its constructors with the innerReal.getConstructors() . 当内部类具有public修饰符时,我可以使用innerReal.getConstructors()获得其构造函数的列表。

But when we delete public modifier of Inner - the list of constructors becomes empty. 但是,当我们删除Inner的public修饰符时,构造函数的列表将为空。 Reflection api lets me to get inner class with its forName() method, but i cant get its instance with the constructor, because it has not any one. 反射api允许我使用其forName()方法获取内部类,但是我无法通过构造函数获取其实例,因为它没有任何实例。

Thanks in advance for any help! 在此先感谢您的帮助! =) =)

尝试getDeclaredConstructors() ,它可以为您提供帮助。

You forgot to set constructor as accessible 您忘记将构造函数设置为可访问

this should work: 这应该工作:

Constructor<?> ctor = innerReal.getConstructor(outerClazz.getClass(), String.class);
ctor.setAccessible(true); // can throw some sort of Exception
AbstractClass resultClass = (AbstractClass) ctor.newInstance(outerClazz, innerReal.getName());

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

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