简体   繁体   中英

How to load java class and its reference class recursively

Image The class diagram like this:

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?

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 {
 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 a = new A();
a.b.c;

You can call Class.forName(“B”) and Class.forName(“C”) to load them in.

However the JVM explicitly delays loading the classes until they are needed, so you won't be able to do this directly.

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.

However if there's no relationship between A and B then you'd have to do the Class.forName(“B”) to do the work.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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