我有一类学生是的Java class.forClass()VS类声明
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")
是相同的声明类与变量 名称。
实际上,它是'Class.forName()',而不是'Class.forClass()'。 –