简体   繁体   English

在java中导入该类时,是导入该类的源代码还是字节码?

[英]Whether we import source code or byte code of a class when importing that class in java?

我已经开始学习 java 中的包。我了解了 import 关键字。现在我怀疑是 .class 文件还是 .java 文件在我们导入 java 中的任何类时被导入。

An import in a Java files does nothing more than allowing you to refer to a class by it's short name rather than it's fully qualified name. Java 文件中的import只是允许您通过短名称而不是完全限定名称来引用类。

So if you use a class named some.package.CoolClass then you can either use that full name everywhere in your code or just put import some.package.CoolClass;因此,如果您使用名为some.package.CoolClass的类,那么您可以在代码中的任何地方使用该全名,也可以将import some.package.CoolClass; on the top and call it just CoolClass in your code.在顶部并在您的代码CoolClassCoolClass

The compiler needs to be able to load the class the you are using (whether or not you imported it) and that means it either needs to find the .class file of that class or also compile the .java file at the same time (ie if you have two classes A and B and compile them both at the same time then each can reference the other, even if there technically aren't any class files of them around at that time).编译器需要能够加载您正在使用的类(无论您是否导入它),这意味着它要么需要找到该类的 .class 文件,要么同时编译 .java 文件(即如果您有两个类AB并同时编译它们,那么每个类都可以引用另一个类,即使当时技术上没有它们的任何类文件)。

At runtime (ie when you actually execute your code) you'll need the .class files of each class you use on your classpath.在运行时(即实际执行代码时),您将需要在类路径中使用的每个类的 .class 文件。 (.java files are not used at runtime). (运行时不使用 .java 文件)。 Again, it doesn't matter if you used an import to use the short name or used the fully qualified name in your code.同样,是使用import来使用短名称还是在代码中使用完全限定名称都没有关系。

Does the compiler use .class or .java files for an import?编译器是否使用 .class 或 .java 文件进行导入?

Answer: .class files, possibly compiling .java files.答: .class 文件,可能编译 .java 文件。

This works, even in the following case (when there are no .class files):这有效,即使在以下情况下(当没有 .class 文件时):

// p/a/A.java
package p.a;
import p.b.B;
public class A {
    public static final A DEFAULT_A = new B();
}

// p/b/B.java
package p.b;
import p.a.A;
public class B extends A {
}

The reason that this (a cyclic dependency) can be dealt with, is that .class files are comparable with .obj / .o object files: there is symbolic information (class and method names) in the .class files.之所以可以处理这个(循环依赖),是因为 .class 文件与 .obj / .o 目标文件相当:.class 文件中有符号信息(类和方法名称)。 And just as the object files are linked with a linker to an executable or library, the java class loader resolves everything.就像目标文件通过链接器链接到可执行文件或库一样,java 类加载器解决所有问题。

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

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