Search code examples
javaclassstaticloader

Why Java class loader executes "static" content, like Class.forName


I googled the difference between ClassLoader and Class.forName, most answer say that Class.forName will operate the "static" section of a class, while ClassLoader doesn't. So I tested this:

public static void main(String[] args) {
    try {
        ClassLoader l = ClassLoader.getSystemClassLoader();
        Class c2 = l.loadClass("C");
        Constructor ctor2 = c2.getConstructor();
        C obj2 = (C) ctor2.newInstance();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

It prints:

static
default ctor

Well, not my expected, why and when does ClassLoader execute "static" section, anyway? If it also executes "static", then what's the core difference between these 2?

Thanks a lot.


Solution

  • l.loadClass("C"); will not leading to execute static initializers, while creating an instance does.

    You can remove below code and try it again:

    Constructor ctor2 = c2.getConstructor();
    C obj2 = (C) ctor2.ne