转到Java字节码 [英] goto in Java bytecode

查看:143
本文介绍了转到Java字节码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以有一天,当我查看维基百科页面上的Java字节码时,我遇到了这个例子:

So the other day when I was looking at the wikipedia page for Java bytecode I came across this example:


考虑以下Java代码:

Consider the following Java code:



  outer:
  for (int i = 2; i < 1000; i++) {
      for (int j = 2; j < i; j++) {
          if (i % j == 0)
          continue outer;
     }
     System.out.println (i);
  }

Java编译器可能会将上面的Java代码转换为字节代码,如下所示,假设以上是一种方法:

A Java compiler might translate the Java code above into byte code as follows, assuming the above was put in a method:

  0:   iconst_2
  1:   istore_1
  2:   iload_1
  3:   sipush  1000
  6:   if_icmpge       44
  9:   iconst_2
  10:  istore_2
  11:  iload_2
  12:  iload_1
  13:  if_icmpge       31
  16:  iload_1
  17:  iload_2
  18:  irem
  19:  ifne    25
  22:  goto    38
  25:  iinc    2, 1
  28:  goto    11
  31:  getstatic       #84; //Field java/lang/System.out:Ljava/io/PrintStream;
  34:  iload_1
  35:  invokevirtual   #85; //Method java/io/PrintStream.println:(I)V
  38:  iinc    1, 1
  41:  goto    2
  44:  return

我注意到goto小字出现几次,在检查 JVM 规范有效。 我的问题是为什么? GOTO是Java中保留但不可用的关键字,那么为什么当我们编写和编译java代码时,它似乎是用goto编译回来的。我想知道这只是在较低级别的编程中总是完成的事情,或者是否因为JVM被信任更有效地使用goto字。最后我很好奇为什么goto被认为是一种不好的做法,它在java代码中被禁止,但似乎在编译时会直接回到你的代码中。

And I notice that little word goto appears a couple of times, which upon checking the JVM specification is valid. My question is why? GOTO is a reserved but unusable keyword in Java, so why when we write and compile java code does it seem to get compiled with goto back into it. I am wondering it this is just the way things have always been done at a lower level of programming, or whether it is because the JVM is trusted to use the goto word more effectively. Ultimately I am curious as to why goto is considered such bad practice that it is prohibited in java code, yet seems to be put straight back into your code when compiled.

推荐答案

Java结构化编程功能,例如循环(用于 / )在具有条件分支( IF .. )和无条件跳转( GOTO )指令的字节码级别。

Java structured programming features such as loops (for/ while) are implemented at the bytecode level with conditional branch (IF..) and unconditional jump (GOTO) instructions.

break 继续到外循环也被视为足够有用&在结构化编程中合法,Java语言具有这些功能(中断/继续标记)。

break or continue to an outer loop are also considered sufficiently useful & legitimate within structured programming, that the Java language has these features (break/ continue to label).

在JVM /字节码级别,这些也是用 GOTO 实现的。

At the JVM/ bytecode level, these are also implemented with GOTO.

参见:

  • https://en.wikipedia.org/wiki/Java_bytecode_instruction_listings
  • http://www.artima.com/underthehood/flowP.html

这篇关于转到Java字节码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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