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

后端 未结 2 1762
后悔当初
后悔当初 2020-12-03 14:49

By default, Sun\'s JVM both lazily loads classes and lazily initializes (i.e. calls their methods) them. Consider the following class, Clin

相关标签:
2条回答
  • 2020-12-03 15:26
    Class.forName("...", true /*initialize*/, getClassLoader());
    

    You were halfways there.

    0 讨论(0)
  • 2020-12-03 15:33

    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!

    0 讨论(0)
提交回复
热议问题