简体   繁体   English

为什么要创建这个类文件?

[英]Why does this class file get created?

In Java all classes are loaded into the JVM dynamically, upon the first use of a class. 在Java中,所有类在第一次使用类时动态加载到JVM中。

Does it mean if i have class in a my source file and I do not make any reference to it then its Class object is not created (ie .class file is not created)? 这是否意味着如果我在我的源文件中有类并且我没有对它进行任何引用,那么它的Class对象就不会被创建(即没有创建.class文件)?

In the sample code below iam not making a refernce to test3 class but still its class object gets created. 在下面的示例代码中,iam没有引用test3类,但仍然创建了它的类对象。

class test1 {
    static {
        System.out.println("static block of test1");
    }
}   
class test2{
    static {
        System.out.println("static block of test2");
    }
}
class test3 {}
class MyExample1 {
    public static void main(String ...strings ) {
    new test1();
    new test2();
    }
}

Why test3.class file gets created? 为什么要创建test3.class文件?

.class file was created at compilation time. .class文件是在编译时创建的。 But, it will be loaded from .class file by first usage (probably). 但是,它将通过第一次使用(可能)从.class文件加载。

From where it should be loaded without .class file?) 应该在没有.class文件的情况下从哪里加载?)

You have to distinguish between the file test3.class (which is created by the compiler) and the class object test3.class of class test3 , which is created on runtime when the class is loaded by the classloader. 您必须区分文件 test3.class (由编译器创建)和类test3类对象 test3.class ,它是在类加载器加载类时在运行时创建的。

The class file is always created if you compile a .java source file (compilation unit) with the class in it (most often class3.java , but it can also be named anything else, if the class is not public) - or implicitely if the class is used by another compiled class. 如果您使用其中的类编译.java源文件(编译单元),则始终会创建类文件 (通常是class3.java ,但如果该类不公开,它也可以命名为其他任何内容) - 或者如果该类由另一个编译的类使用。

The class object is created by the classloader when the class is first loaded - this occurs whenever it is needed, or earlier. 首次加载时, 类对象由类加载器创建 - 只要需要或更早,就会发生这种情况。 The normal URLClassLoader loads your class from a file with the same name, but in principle the data could also be generated on the fly, loaded from a database or similar. 普通的URLClassLoader从具有相同名称的文件加载您的类,但原则上,数据也可以动态生成,从数据库或类似文件加载。 It (the class) then is initialized by invoking the static blocks. 然后通过调用static块来初始化它(类)。 (The initialization is a second step, not necessarily at the same time, but both are before your first use of the class.) (初始化是第二步,不一定是同时进行,但两者都是在你第一次使用该类之前。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM