简体   繁体   English

如何递归加载 java class 及其参考 class

[英]How to load java class and its reference class recursively

Image The class diagram like this:图像 class 图如下:

class A {
  B b;
}

class B {
  C c;
}

class C {
}

I wanna load class A、B and C at startup before calling to A、B or C, but when I try class.forName("A") the JVM only loads class A, how can I load all classes from A to C recursively? I wanna load class A、B and C at startup before calling to A、B or C, but when I try class.forName("A") the JVM only loads class A, how can I load all classes from A to C recursively ?

if you want to load class B inside Class A, and Class C inside B, You need to define constructor to new an instance如果要在 Class A 和 Class Z0D61F8370CAD1D412F80B84D143E1257 中加载 class B

class A {
 B b;
  public A() { b = new B()}
}

class B {
  C c;
  public B() {c = new C()}
}

class C {
}

Then, when you new A, it will create instance class B,C and access it likes然后,当您新建 A 时,它将创建实例 class B,C 并访问它喜欢

A a = new A();
a.b.c;

You can call Class.forName(“B”) and Class.forName(“C”) to load them in.您可以调用Class.forName(“B”)Class.forName(“C”)来加载它们。

However the JVM explicitly delays loading the classes until they are needed, so you won't be able to do this directly.但是,JVM 明确延迟加载类,直到需要它们,因此您将无法直接执行此操作。

If you really want to achieve this behaviour (and there are type references from A to B) then you can use reflection to list all declared methods of A and declared fields of A. If any of those include B, then this list will cause the classes to be brought in.如果你真的想实现这种行为(并且有从 A 到 B 的类型引用),那么你可以使用反射来列出 A 的所有声明方法和 A 的声明字段。如果其中任何一个包括 B,那么这个列表将导致要引入的课程。

However if there's no relationship between A and B then you'd have to do the Class.forName(“B”) to do the work.但是,如果 A 和 B 之间没有关系,那么您必须执行Class.forName(“B”)来完成这项工作。

Finally it's not clear why you are wanting to do this.最后,尚不清楚您为什么要这样做。 Can you expand your question to include the “why” and not just the “how” because there may be a better way.您能否扩展您的问题以包括“为什么”而不仅仅是“如何”,因为可能有更好的方法。

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

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