Java类中允许的最大代码行数?

时间:2020-03-06 14:28:54  来源:igfitidea点击:

.java文件可以包含几行代码?是否取决于所使用的JVM?

解决方案

我相信每种方法的字节码大小限制为64kb。

为了扩展Jonas的响应,《 Java虚拟机规范》第4.8节" Java虚拟机代码的约束"说:

The Java virtual machine code for a
  method, instance initialization method
  (§3.9), or class or interface
  initialization method (§3.9) is stored
  in the code array of the Code
  attribute of a method_info structure
  of a class file. This section
  describes the constraints associated
  with the contents of the
  Code_attribute structure.

继续第4.8.1节,静态约束

The static constraints on a class file
  are those defining the well-formedness
  of the file. With the exception of the
  static constraints on the Java virtual
  machine code of the class file, these
  constraints have been given in the
  previous section. The static
  constraints on the Java virtual
  machine code in a class file specify
  how Java virtual machine instructions
  must be laid out in the code array and
  what the operands of individual
  instructions must be.
  
  The static constraints on the
  instructions in the code array are as
  follows:
  
  ...
  
  
  The value of the code_length item must be less than 65536.
  
  
  ...

因此,一个方法的每个方法的字节码限制为65535个字节。 (请参阅下面的注释)

有关JVM的更多限制,请参见第4.10节Java虚拟机的限制。

注意:尽管JVM的设计显然存在问题,但如果65535字节处的指令是1字节长的指令,则它不受异常处理程序的保护,请参见4.10节的脚注4.

我记得实际上曾经在Tomcat 4的一个复杂的JSP页面中遇到过这个限制(过去人们仍在使用JSP的时候)。从JSP生成的java文件的方法太大,无法编译,我想我必须将文件拆分或者进行其他一些特技,从可读性上来说,这当然是一个好主意。

Sun的错误跟踪器告诉我,有些人仍然遇到相同的问题。

"代码行"没有限制,但是总大小是有限制的。每种方法都有64kb的限制。

我只是用代码生成工具碰到过这一点。

如果我们即将接近极限,请当心。许多性能分析和监视工具都使用字节码插入。如果我们离得太近,它们可以将我们推到顶部。更糟糕的是,它们经常在编译后更改类文件。一切都可以在开发环境中编译并运行,但是当我们在Test或者QA中打开监视工具时,它会崩溃。