简体   繁体   English

类加载:编译时或运行时

[英]Class Loading: Compile time or Runtime

Is java class loaded at compile time or Runtime? Java类是在编译时还是在运行时加载? I know you can dynamically load a java class using your own Class Loaders or calling Class.forName("fully qualified name of java file") . 我知道您可以使用自己的类加载器或调用Class.forName("fully qualified name of java file")动态加载Java类。

But if I am not using any of the above techniques then does it means that Java classes are loaded at compile time? 但是,如果我没有使用任何上述技术,那么这是否意味着Java类是在编译时加载的?

No. The JLS explains how loading and linking is runtime. 。JLS解释了加载和链接是如何运行的。 Any binary-compatible revision of a class can be thrown in place of an existing class. 可以抛出类的任何二进制兼容版本,以代替现有类。

A class is compiled with a symbolic reference to other classes, not the code of those classes. 使用符号引用引用其他类而不是这些类的代码来编译类。

However with certain non-JVM compilers like GCJ classes can be compiled ahead of time into one executable. 但是,对于某些非JVM编译器,例如GCJ类,可以提前将其编译为一个可执行文件。

Classes are loaded at runtime to execute their code. 在运行时加载类以执行其代码。

Classes are loaded at compile time to check code using the class for type safety. 在编译时加载类以使用类型安全性检查该类的代码。
Whenever you write code that uses a class (eg, calling a method on it), the compiler needs to load that class to make sense of your code (eg, to check methods or base type) 每当您编写使用类的代码(例如,在其上调用方法)时,编译器都需要加载该类以理解您的代码(例如,检查方法或基本类型)

At compile time nothing is loaded. 在编译时,不会加载任何内容。 At compile time classes are just generated from sources. 在编译时,类只是从源生成的。

The difference could be if a class is loaded by the ClassLoader when the JVM powers up or if you do it dynamically during the execution, but they are two sides of the same medal. 不同之处可能是在JVM通电时是由ClassLoader加载的ClassLoader ,还是在执行过程中动态地进行操作,但是它们是同一枚勋章的两个方面。

In both cases they are loaded dynamically, but in the former this is done as soon as the JVM starts. 在这两种情况下,它们都是动态加载的,但是在前一种情况下,JVM启动后就完成了。

As many others have stated, classes are loaded at runtime unless you are using an AOT compiler to allow them to run in non-JVM environments. 正如许多其他人所述,除非您使用AOT编译器允许它们在非JVM环境中运行,否则这些类将在运行时加载。 If you want to read up all the details on how the Java Virtual Machine starts up, initializes and loads the first then subsequent classes you can take a look at the Java SE 7 specifications . 如果您想阅读有关Java虚拟机如何启动,初始化和加载第一个以及随后的类的所有详细信息,可以查看Java SE 7规范

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

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