读取Java字节码指令:数字是什么意思? [英] Reading a Java bytecode instruction: What does the number mean?

查看:723
本文介绍了读取Java字节码指令:数字是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读java字节码,看到了这个:

I was reading java bytecode and saw this:

getfield #5 (Field java.lang.String name)

#5 是什么意思?

如何用字节码编写程序?

And how can I write a program in bytecode?

推荐答案

Java类文件和字节码

Java类文件(字节码文件)由不同的组件组成:

Java class files (bytecode-files) is composed by different components:

http://en.wikipedia.org/wiki/Java_class_file


  • 幻数:0xCAFEBABE

  • 类文件格式的版本:类文件的次要版本和主要版本

  • 常量池:类的常量池

  • (...)

  • 字段:任意类中的字段

  • 方法:类中的任何方法

  • 属性:类的任何属性(例如源文件的名称等) 。)

  • Magic Number: 0xCAFEBABE
  • Version of Class File Format: the minor and major versions of the class file
  • Constant Pool: Pool of constants for the class
  • (...)
  • Fields: Any fields in the class
  • Methods: Any methods in the class
  • Attributes: Any attributes of the class (for example the name of the sourcefile, etc.)

数字#5仅指恒定池中的位置。在该位置找到CONSTANT_FieldRef,其中包含对CONSTANT_NameAndType以及其他属性的引用。 CONSTANT_NameAndType包含对CONSTANT_Utf8的引用(包含实际的字符串/名称。)

The number #5 simply refers to a location in the constant pool. And in that position a CONSTANT_FieldRef is found which contains a reference to a CONSTANT_NameAndType among other attributes. And CONSTANT_NameAndType contains a reference to a CONSTANT_Utf8 (which contains the actual string/name.)

所以流程如下所示:

getfield #number -> FieldRef -> NameAndType -> Utf8 -> string

http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html

因此,不是在每个 getfield 指令中保存整个字符串,而是保存一个数字。这提高了类文件中解释器(或JIT)和空间的性能。

So instead of saving a whole string in each getfield instruction a number is saved. This improves performance in the interpreter (or JIT) and space in the class file.

手写字节码

手写的字节码可以用这个工具组装成一个类文件(它包含很多例子):

Hand-written bytecodes can be assembled to a class file with this tool (it contains a lot of examples):

http://jasmin.sourceforge.net/

这篇关于读取Java字节码指令:数字是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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