Search code examples
javaclassloader

What is Causing a Java Class to be Loaded?


I am trying to open a Java class file, instrument the bytecode and save the class file before the class is loaded into the JVM. My problem is that a class is being loaded "too soon" into the JVM. The bytecode is instrumented after the class is loaded into the JVM.

-verbose:class prints when each class is loaded but it doesn't tell me what triggered the JVM to load the class. How do I get a call stack which shows the class being loaded?

Putting a breakpoint in the following code, shows the call stack when the class is initialized and not loaded.

static
{
    System.out.println("Initialized!");
}

Note: I know I could use a Java agent to do this and guarantee the bytecode is instrumented. But, I choose this route for various reasons.


Solution

  • I opened java.lang.ClassLoader and set a conditional breakpoint in loadClass(String name, boolean resolve). The condition is arg0.endsWith("MyClass") where arg0 is the name parameter. When the breakpoint is triggered, the IDE displays the call stack. Several frames down on the call stack shows me why the class is being loaded.

    Note: This condition works in Eclipse IDE and may need a little tweaking in other IDEs.