简体   繁体   English

Java:如何加载已经在类路径上的类(及其内部类)?

[英]Java: How to load a class (and its inner classes) that is already on the class path?

How can I load a class that is already on the class path, instantiate it, and also instantiate any inner classes defined within it? 如何加载已经在类路径上的类,实例化它,并实例化其中定义的任何内部类?

EG: 例如:

public class TestClass {


    public class InnerClass { }

}

Inner classes cannot exist outside the parent class. 内部类不能存在于父类之外。 You need to construct the parent class first. 您需要首先构造父类。 Without reflection this would look like: 没有反思,这看起来像:

InnerClass innerClass = new TestClass().new InnerClass();

In reflection, you need to pass the parent class in during construction of the inner class. 在反射中,您需要在构造内部类时传递父类。

Object testClass = Class.forName("com.example.TestClass").newInstance();
for (Class<?> cls : testClass.getClass().getDeclaredClasses()) {
    // You would like to exclude static nested classes 
    // since they require another approach.
    if (!Modifier.isStatic(cls.getModifiers())) {
        Object innerClass = cls
            .getDeclaredConstructor(new Class[] { testClass.getClass() })
            .newInstance(new Object[] { testClass });
    }
}

As a side note, given that your primary question has been answered - often people will declare inner classes as in your example above, without giving a thought to whether they can be static inner classes instead. 作为旁注,鉴于您的主要问题已得到解答 - 通常人们会像上面的示例中那样声明内部类,而不考虑它们是否可以是静态内部类。

In my experience, the vast majority of (non-anonymous) inner classes can be static, as they don't need to access their parent class' instance members. 根据我的经验,绝大多数(非匿名)内部类可以是静态的,因为它们不需要访问其父类的实例成员。 Declaring the inner class as static in this case is both more efficient (as the runtime doesn't need to define a new class for each parent instance), less confusing (since new TestClass().new InnerClass().getClass() != new TestClass().new InnerClass().getClass() ) and easier to instantiate if you don't have an appropriate instance of TestClass handy. 在这种情况下将内部类声明为静态更有效(因为运行时不需要为每个父实例定义新类),更少混淆(因为new TestClass().new InnerClass().getClass() != new TestClass().new InnerClass().getClass() )如果没有适当的TestClass实例, new TestClass().new InnerClass().getClass() != new TestClass().new InnerClass().getClass()容易实例化。

So if this applies to you, you could (and arguably should) declare you inner class thusly: 所以,如果这适用于你,你可以 (并且可以说)应该如此声明你的内部阶级:

public class TestClass {

    public static class InnerClass { }

}

and then you can simply instantiate it as new TestClass.InnerClass() . 然后你可以简单地将它实例化为new TestClass.InnerClass()

(If you need to access member fields from within InnerClass, then just ignore all this of course!) (如果你需要从InnerClass中访问成员字段,那么当然要忽略所有这些!)

Class.forName("your classname").newInstance().

仅当构造函数实例化它们时,才会实例化内部类。

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

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