为什么 Java 将方法的大小限制为 65535 字节?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5689798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 12:20:29  来源:igfitidea点击:

Why does Java limit the size of a method to 65535 byte?

java

提问by Konstantin Weitz

I just compiled the following code

我刚刚编译了以下代码

public class A {
    public static void main(String... args) {
        int i = 3;
        ++i; 
        ++i;
        ++i;
        ++i;
        ++i;
        ++i;
        ++i;
        ++i;
        // repeat writing the expression ++i for 20,000 times

        System.out.println(i);
    }
}

And got the following error message

并收到以下错误消息

The code of method main(String...) is exceeding the 65535 bytes limit

方法 main(String...) 的代码超过了 65535 字节的限制

Why does Java implement this limit? I don't see the rational since Java does include a goto_w instruction.

Java 为什么要实现这个限制?我没有看到理性,因为 Java 确实包含 goto_w 指令。

回答by WhiteFang34

See the Java Virtual Machine Specificationsection 4.10:

请参阅Java 虚拟机规范第 4.10 节:

4.10 Limitations of the Java Virtual Machine

  • The amount of code per non-native, non-abstract method is limited to 65536 bytes by the sizes of the indices in the exception_table of the Code attribute (§4.7.3), in the LineNumberTable attribute (§4.7.8), and in the LocalVariableTable attribute (§4.7.9).

4.10 Java 虚拟机的局限性

  • 每个非本机、非抽象方法的代码量限制为 65536 字节,这取决于 Code 属性(第 4.7.3 节)、LineNumberTable 属性(第 4.7.8 节)的 exception_table 中的索引大小,以及在 LocalVariableTable 属性中(第 4.7.9 节)。

There's few good reasons to have a method that long in an object-oriented programming language.

在面向对象的编程语言中使用如此长久的方法没有什么好的理由。