提高Java程序动态性的一个新途径

2015-10-21 18:12:24严忠林
计算机时代 2015年9期

严忠林

摘 要: 为支持Groovy、JRuby等新的动态类型语言,JDK1.7在Java虚拟机上特意引入了新的动态调用指令。文章提出将其应用于Java程序,在生成的Java类文件中用它替换某些成员访问指令,由此可以突破Java原本固有的运行模式,引入满足应用需要的新运行机制,使程序更简单、灵活,提高开发效率。同时分析了原有成员访问指令的局限,讨论了新的动态调用指令的优势,给出了指令替换的实现方法。

关键词: 动态调用指令; 成员访问; Java虚拟机; Java类文件

中图分类号:TP311 文献标志码:A 文章编号:1006-8228(2015)09-01-03

New approach to improve dynamic of Java programs

Yan Zhonglin

(College of information, mechanical and electrical engineering, Shanghai Normal University, Shanghai 200234, China)

Abstract: Since JDK1.7, the invokedynamic instruction has been introduced to JVM to support dynamically typed languages such as Groovy, JRuby. This paper proposes replacing some appropriate member access instructions with it in a Java class file, which may break Java inherent operation mode, introduce a new mechanism that meets the application needs, make the program more simple and flexible, and improve development efficiency. At the same time, the limitations of the original member access instruction and the advantages of the invokedynamic instruction is analyzed, and the method to realize the instruction replacement is given.

Key words: invokedynamic instruction; member access; JVM; Java class file

0 引言

自JDK1.7起,为了方便在JVM上实现像JRuby、Jython、Groovy、Clojure那样的动态类型语言,在虚拟机层面引入了动态类型语言支持(JSR-292)[1]。与Java这样的静态类型语言不同,动态类型语言的变量、方法不需要事先声明,直到运行时,才根据当时数据的实际类型决定所要进行的操作。例如对表达式a+b,要一直到运行至此处时,才根据a、b当时的数值,决定是做整数加、浮点数加,还是字符串加。因此对于这类语言,计算机所执行的代码不是在编译时,而要到运行时才确定。

所谓动态性是指这种能根据运行时状态,自主决定实际操作的能力。Java本是静态类型语言,大多数操作都不能在运行时改变,与此相适应的JVM指令也因此很难满足动态类型语言的要求。为改变这种状况,JSR-292引入了新的动态调用指令invokedynamic,它执行的操作取决于内含的方法句柄(MethodHandle)。MethodHandle是新添加的java.lang.invoke包中的类,是对类内各种成员的引用[2]。使用它,动态类型语言就能按照自己的规则,根据运行时参数和其他状态,实现希望的操作。……

登录APP查看全文