java class.forClass()vs类声明(java class.forClass() vs Class declaration)

我有一个班的学生是

package org.ahmed; public class Student { public Student() { // TODO Auto-generated constructor stub System.out.println("Generated constructor"); } static { // static block System.out.println("Hello world static"); } { // insance block System.out.println("Hello world non static"); } }

接着

public class Main { public static void main(String[] args) throws ClassNotFoundException { Class.forName("org.ahmed.Student"); // this line causing static block execution in Student class // Student s; // this line doesn't execute the static block. } }

我明白通过使用Class.forClass()我们可以在运行时动态运行任何类。 但在其他情况下,我对静态块有一些疑问。

如果我在我的main方法中使用Class.forClass("org.ahmed.Student") ,那么它执行Student的静态块。 但是,如果我在main方法中声明Student s不执行静态块。 我认为Class.forClass("ClassName")与用变量名声明类相同。

I have one class Student which is

package org.ahmed; public class Student { public Student() { // TODO Auto-generated constructor stub System.out.println("Generated constructor"); } static { // static block System.out.println("Hello world static"); } { // insance block System.out.println("Hello world non static"); } }

and then

public class Main { public static void main(String[] args) throws ClassNotFoundException { Class.forName("org.ahmed.Student"); // this line causing static block execution in Student class // Student s; // this line doesn't execute the static block. } }

I understand by using Class.forClass() we can dynamically run any class in runtime. But I have some question in other case regarding static block.

If I use Class.forClass("org.ahmed.Student") in my main method, then it's executing the static block of Student. But if I declare Student s in main method its doesn't execute the static block. I thought Class.forClass("ClassName") is same as declaring class with a variable name.

最满意答案

当您使用Class.forName("org.ahmed.Student")您实际上强制JVM加载该类并调用其静态块。 你可以在这里阅读更多。

When you use Class.forName("org.ahmed.Student") you actually force the JVM to load the class and invoke its static blocks. You can read more here.

更多推荐