Java:如何加载已经在类路径中的类(及其内部类)? [英] Java: How to load a class (and its inner classes) that is already on the class path?
本文介绍了Java:如何加载已经在类路径中的类(及其内部类)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何加载已经在类路径中的类,实例化它,以及实例化其中定义的任何内部类?
EG:
公共类TestClass {
公共类InnerClass {}
}
解决方案
内部类不能存在于父类之外。您需要先构造父类。不经思考,它看起来像:
InnerClass innerClass = new TestClass()。new InnerClass();反思,您需要在构造内部类时将父类传递进来。 对象testClass = Class.forName( com.example.TestClass)。newInstance();
for(Class<?> cls:testClass.getClass()。getDeclaredClasses()){
//您想排除静态嵌套类
//,因为它们需要另一种方法。
if(!Modifier.isStatic(cls.getModifiers())){
对象innerClass = cls
.getDeclaredConstructor(new Class [] {testClass.getClass()))
.newInstance(new Object [] {testClass});
}
}
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 });
}
}
这篇关于Java:如何加载已经在类路径中的类(及其内部类)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文