0

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.

Hind Forsum
  • 9,717
  • 13
  • 63
  • 119

1 Answers1

2

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
xingbin
  • 27,410
  • 9
  • 53
  • 103