java一个文件两个class,为什么Java在编译时生成多个.class文件?

Java编译源代码时,每个类(包括内部类和接口)生成一个.class文件,这是为了保持与早期Java版本的兼容性和简化类加载。历史原因是Java1.0不支持嵌套类,而1.1为了兼容性选择了使用独立的.class文件。此外,这种格式简化了类加载过程,避免了嵌入式格式可能带来的复杂性。虽然这可能导致在某些情况下使用Class.forName()加载内嵌类时的不便,但解决方案相对直接。
摘要由CSDN通过智能技术生成

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?

解决方案

In response to @Jon Skeet's rhetorical question:

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

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.

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.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值