简体   繁体   English

我如何知道在内部(成员)类上使用哪个构造函数?

[英]How can I tell which constructor to use on an inner (member) class?

Reflective instantiation of an inner class requires a constructor that takes a synthetic parameter, the instance of the enclosing class. 内部类的反射实例化需要一个带有综合参数的构造函数,即封闭类的实例。 If the inner class is static, then there is no such constructor. 如果内部类是静态的,则没有此类构造函数。

I can tell that a class is an inner class using the Class.isMemberClass() method, but I can't see a neat way of determining whether or not the member class is static or not, which is how I would expect to figure out which constructor to call. 我可以使用Class.isMemberClass()方法告诉一个类是一个内部类,但是我看不到一种确定成员类是否为静态的灵巧方法,这就是我希望弄清楚的方式调用哪个构造函数。

Is there a neat way to tell? 有一个整洁的方法可以告诉吗?

See the Examining Class Modifiers tutorial. 请参阅“ 检查类修饰符”教程。 I think it's something like 我觉得有点像

Modifier.isStatic(myClass.getModifiers());

David is correct. 大卫是正确的。 I'm just going to post what you mean by 我只是要发表你的意思

Reflective instantiation of an inner class requires a constructor that takes a synthetic parameter, the instance of the enclosing class. 内部类的反射实例化需要一个带有综合参数的构造函数,即封闭类的实例。

for people like myself that needed to try it out: 对于像我这样需要尝试的人:

public class Outer {
    public String value = "outer";

    public static void main(String[] args) throws Exception {
        int modifiers = StaticNested.class.getModifiers();
        System.out.println("StaticNested is static: " + Modifier.isStatic(modifiers));

        modifiers = Inner.class.getModifiers();
        System.out.println("Inner is static: " + Modifier.isStatic(modifiers));

        Constructor constructor = Inner.class.getConstructors()[0]; // get the only one
        Inner inner = (Inner) constructor.newInstance(new Outer()); // the constructor doesn't actually take arguments
    }

    public static class StaticNested {

    }

    public class Inner {
        public Inner() {
            System.out.println(Outer.this.value);
        }
    }
}

prints 版画

StaticNested is static: true
Inner is static: false
outer

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

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