1、计算机专业文献翻译在 JDK 早期版本中使用 Java 5 的语言特性Using Java 5 language features in earlier JDKJava 5 added a number of powerful language features: generics, enumerations, annotations, autoboxing, and the enhanced for loop. However, many shops are still tied to JDK 1.4 or earlier and may be for some time to come.
2、But its still be possible for those developers to take advantage of these powerful language features while continuing to deploy on earlier JVMs. Brian Goetz returns from his hiatus in this installment of Java theory and practice to demonstrate how.With Java 6.0 being newly released, you might think
3、the Java 5 language features are old news. But even now, when I ask developers which version of the Java platform they are using in development, typically only half are using Java 5 - and the other half are jealous. They are eager to use the language features added in Java 5 such as generics and ann
4、otations, but a number of factors still prevent many from doing so. One category of developers unable to take advantage of Java 5 features are those who develop components, libraries, or application frameworks. Because their customers may still be using JDK 1.4 or earlier and classes compiled with J
5、ava 5 cannot be loaded by JDK 1.4 or previous JVMs, using Java 5 language features would limit their customer base to companies that have already transitioned to Java 5. Another group of developers often held back from using Java 5 are those working with Java EE. Many shops will not use Java 5 with
6、Java EE 1.4 or earlier for fear that it will not be supported by their application server vendor. But it may be a while before those shops transition to Java EE 5. In addition to the lag time between the Java EE 5 and Java SE 5 specifications, commercial Java EE 5 containers are not necessarily avai
7、lable as soon as the ink is dry on the specification, businesses do not necessarily upgrade their applications servers as soon as the next version is available, and even after upgrading their application server, it may take some time to certify their applications on the new platform. Java 5 language
8、 feature implementationThe language features added in Java 5 - generics, enumerations, annotations, autoboxing, and the enhanced for loop - required no change to the JVM instruction set, and are almost entirely implemented in the static compiler (javac) and class libraries. When the compiler encount
9、ers the use of generics, it attempts to verify that type safety is preserved (emitting an unchecked cast warning if it cannot) and then emits bytecode that is identical to what would be produced from equivalent nongeneric code, casts and all. Similarly, autoboxing and the enhanced for loop are simpl
10、y syntactic sugar for equivalent, but more verbose, idioms, and enumerations are compiled into ordinary classes. In theory, you could take the class files produced by javac and load them in earlier JVMs, which was, in fact, the intention when JSR 14 (the Java Community Process working group responsi
11、ble for generics) was convened. However, other issues (such as retention of annotations) forced the class file version to be changed between Java 1.4 and Java 5, which prevents code compiled for Java 5 to be loaded by earlier JVMs. Further, some of the language features added in Java 5 have dependen
12、cies on the Java 5 libraries. If you compile a class with javac -target 1.5 and try to load it on an earlier JVM, youll get an UnsupportedClassVersionError because the -target 1.5 option generates classes with a class file version of 49, and JDK 1.4 only supports class file versions through 48. The
13、for-each loopThe enhanced for loop, sometimes called the for-each loop, is translated by the compiler as if the programmer had supplied the equivalent old-style for loop. The for-each loop can iterate over the elements of an array or of a collection. Listing 1 shows the syntax of iterating over a co
14、llection with the for-each loop: Listing 1. The for-each loopCollection fooCollection = .for (Foo f : fooCollection) doSomething(f);The compiler translates this code into the equivalent iterator-based loop, as shown in Listing 2: Listing 2. Iterator-based equivalent for Listing 1for (Iterator iter=f
15、.iterator(); f.hasNext();) Foo f = (Foo)iter.next(); doSomething(f);How does the compiler know that the supplied argument has an iterator() method? The architects of the javac compiler could have built in understanding of the collections framework, but this approach would have been unnecessarily res
16、trictive. Instead, a new interface was created, java.lang.Iterable (see Listing 3), and the collection classes were retrofitted to implement Iterable. This way, container classes that do not build on the core collections framework can still take advantage of the new for-each loop. But doing so creat
17、es a dependency on the Java 5 class library because Iterable is not present in the JDK 1.4 library. Listing 3. The Iterable interfacepublic interface Iterable Iterator iterator();Enumerations and autoboxingJust like the for-each loop, enumerations require support from the class library. When the com
18、piler encounters an enumerated type, it generates a class that extends the library class java.lang.Enum. But, just like Iterable, the Enum class is not present in the JDK 1.4 class library. Similarly, autoboxing relies on the valueOf() methods being added to the primitive wrapper classes (such as In
19、teger). When boxing requires conversion from int to Integer, rather than calling new Integer(int), the compiler generates a call to Integer.valueOf(int). The implementation of the valueOf() methods employs the flyweight pattern to cache the Integer objects for commonly used integer values (the Java
20、6 implementation caches integers from -128 to 127), which may improve performance by eliminating redundant instantiations. And, just like Iterable and Enum, the valueOf() methods are not present in the JDK 1.4 class library. VarargsWhen the compiler encounters a method defined with a variable-length
21、 argument list, it converts it into a method that takes an array of the appropriate component type; when the compiler encounters a call to a method with a variable-length argument list, it boxes the arguments into an array. AnnotationsWhen an annotation is defined, it can be annotated with Retention
22、, which determines what the compiler will do with classes, methods, or fields that possess that annotation. The defined retention policies are SOURCE (discard annotation data at compilation), CLASS (record annotations in the class file), or RUNTIME (record annotations in the class file and retain th
23、em at runtime so they can be accessed reflectively). Other library dependenciesPrior to Java 5, when the compiler encountered an attempt to concatenate two strings, it used the helper class StringBuffer to perform the concatenation. In Java 5 and later, it instead generates calls to the new StringBu
24、ilder class, which is not present in the JDK 1.4 and earlier class libraries. Accessing Java 5 featuresBecause of dependencies of language features on library support, even if the class files produced by the Java 5 compiler could be loaded by earlier JVM versions, execution would still fail because
25、of class loading errors. However, it should be possible to solve these problems by suitably transforming the bytecode because these missing classes do not contain substantial new functionality. JSR 14During the development of the Java generics specification (and other language features added in Java
26、 5), experimental support was added to the javac compiler to allow it to consume Java 5 language features and generate bytecode that could be run on a Java 1.4 JVM. While these features are not supported (or even documented), they are used by a number of open source projects to allow developers to c
27、ode using Java 5 language features and produce JAR files that can be used on earlier JVMs. And, now that javac is open source, it is possible the features might be supported by a third party. To activate these features, you can invoke javac with the -source 1.5 and -target jsr14 options. The JSR 14
28、target mode of javac causes the compiler to emit JDK 1.4-compatible bytecode corresponding to Java 5 language features: Generics and varargs: The casts inserted by the compiler in the presence of generics have no dependency on the class library, and so they can execute equally well on a pre-5 JVM. S
29、imilarly, the code generated by the compiler in the presence of variable-length argument lists has no dependency on the class library. for-each loop: When iterating over an array, the compiler generates an induction variable and the standard array iteration idiom. When iterating over a Collection, t
30、he compiler generates the standard iterator-based idiom. When iterating over a non-Collection Iterable, the compiler produces an error. Autoboxing: Rather than generating calls to the valueOf() method in the wrapper class, the compiler generates calls to the constructor instead. String concatenation
31、: The JSR 14 target mode of javac causes the compiler to generate calls to StringBuffer instead of StringBuilder. Enumerations: The JSR 14 target mode of javac has no special support for enumerations. Code that attempts to use enumerations will fail with a NoClassDefFoundError looking for the java.l
32、ang.Enum base class. Using the JSR 14 target mode allows you to write code that uses generics, autoboxing, and the for-each loop in the easy cases, which may suffice for many projects. It is convenient, if unsupported, and the compiler generates mostly compatible bytecode in a single pass. RetroweaverThere are certain Java 5 language features not supported by the JSR 14 target mode (such as Iterable and enumerations). An alternate approach, taken by open-source projects such as Retroweaver and Retrotranslator, is to generate bytecode using -ta
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1