How do you disable lazy class loading/initialization in Sun's JVM?

こ雲淡風輕ζ 提交于 2019-11-27 14:44:28

There is no way to do this. The JLS says, in §12.4.1 When Initialization Occurs (emphasis mine):

Initialization of a class consists of executing its static initializers and the initializers for static fields declared in the class. [...]

A class or interface type T will be initialized immediately before the first occurrence of any one of the following:

  • T is a class and an instance of T is created.
  • T is a class and a static method declared by T is invoked.
  • A static field declared by T is assigned.
  • A static field declared by T is used and the field is not a constant variable (§4.12.4).
  • T is a top-level class, and an assert statement (§14.10) lexically nested within T is executed.

Invocation of certain reflective methods in class Class and in package java.lang.reflect also causes class or interface initialization. A class or interface will not be initialized under any other circumstance.

A Java implementation which initialized classes as soon as they were loaded would violate the JLS.

Although what you could do would be to use the JVM instrumentation API to write a ClassFileTransformer which added a static block to every class which explicitly initialized its referenced classes (via Class.forName, probably). As soon as one class gets initialized, all the classes reachable from it will be initialized. That might give you the result you're after. It's quite a lot of work, though!

Class.forName("...", true /*initialize*/, getClassLoader());

You were halfways there.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!