为什么Java在编译时生成多个.class文件? [英] Why does Java generate Multiple .class files on compilation?

查看:758
本文介绍了为什么Java在编译时生成多个.class文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,在编译时,我们为源文件中定义的每个类(包括嵌套类和接口)获取.class文件。

生成多个.class文件的原因是什么?
是为了简化课程的重复性吗?
为什么不为一个.java文件生成一个.class?

In Java, on compilation we get a .class file for each class( including nested classes and interfaces) defined in the source file.

What is the reason for this multiple .class file generation?
Is it for simplifying the reusablity of the class?
Why not generate one .class for one .java file?

推荐答案

回应@Jon Skeet的修辞问题:

In response to @Jon Skeet's rhetorical question:


然后另一个类引用Bar,因此JVM需要它的代码......你会如何建议找到该文件?

Another class then refers to Bar, so the JVM needs the code for it... how would you suggest it finds the file?

假设(假设)Java类文件格式通过将它们嵌入最外层的类文件中来表示嵌套/内部类。 Bar的二进制名称是 Lsome / pkg / Foo $ Bar; 。类加载器可以 $ 字符处拆分名称,使用第一部分找到Foo的类文件,然后导航到嵌入式Bar类表示。

Suppose (hypothetically) that the Java classfile format represented nested / inner classes by embedding them in the classfile for the outermost class. The binary name for the Bar is "Lsome/pkg/Foo$Bar;". The class loader could split the name at the "$" character, use the first part to locate the classfile for Foo, and then navigate to the embedded Bar class representation.

我认为内部/嵌套类具有单独的类文件的真正原因是历史性的。 IIRC,Java 1.0不支持嵌套或内部类,因此相应的类文件格式不需要处理它们。当创建Java 1.1(支持内部/嵌套类)时,Sun希望类文件格式与Java 1.0编译器生成的类文件兼容。因此,他们选择使用二进制类名中的保留 $ 字符将内部/嵌套类实现为单独的类文件。

I think that the real reason that inner/nested classes have separate classfiles is historical. IIRC, Java 1.0 did not support nested or inner classes, and hence the corresponding classfile formats did not need to deal with them. When Java 1.1 was created (supporting inner/nested classes), Sun wanted the classfile format to be compatible with the classfiles produced by the Java 1.0 compiler. So they chose to implement inner / nested classes as separate classfiles, using the reserved "$" character in the binary classname.

第二个可能的原因是,与假设的嵌入格式相比,平面格式简化了类加载。

A second possible reason is that the flat format simplifies class loading compared to a hypothetical embedded format.

最后,他们没有令人信服的理由不使用平面文件格式。当一些程序员想要使用 Class.forName()来加载内部类时,它可能会产生一些小问题,但这种情况很少发生......并且解决方案是直接的 - 前进。

And finally, there was (and still is) no compelling reason for them NOT to use a flat file format. It maybe creates some minor head-scratching when some programmer wants to load inner classes using Class.forName() but that is pretty rare occurrence ... and the solution is straight-forward.

这篇关于为什么Java在编译时生成多个.class文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆