Java SE 6 new characteristics: Instrumentation new features
Level: Intermediate
Rui Hu (ruihu@cn.ibm.com), software engineers, IBM
Lu:jing (purefire@126.com), software engineers, IBM
May 16, 2007
By the end of 2006, Sun announced Java Standard Edition 6 (Java SE 6) of the final version, code-named Mustang (Mustang). With Tiger (Java SE 5), the Mustang in a good performance upgrade. Tiger and the API library compared to the substantial strengthening, although the Mustang in the new API is not doing too much of, but also provides many useful and convenient features: in the script, WebService, XML, the compiler API, database , JMX, networks and Instrumentation both good new features and capabilities to strengthen. This series of articles mainly on Java SE 6 in the library of API some of the new features and some of the examples and explain to help in the development of better programming practice of the use of Java SE 6, increase development efficiency.
This paper is the first of the series, introduced in Java SE 6 Instrumentation the new features.
References) of the presentation.
Instrumentation the biggest role, is the definition of dynamic change and operation. Java SE 5 and the follow-up version, developers can an ordinary Java programs (with the main function of Java) running through-javaagent parameters specify a specific jar files (including Instrumentation Agents) to start the agent Instrumentation .
In the Java SE 5, a developer can allow Instrumentation agents operating in the main function, former executive. Summary says is the following steps:
- Prepared premain function
Preparation of a Java class, which contains the following two methods of any one
Public static void premain (String agentArgs, Instrumentation inst), [1] public static void premain (String agentArgs), [2]
Among them, the priority [1] [2] level than high priority will be the implementation of ([1] and [2] At the same time, the court has been neglected [2]).
In this premain function, a developer can carry out the type of operation.
AgentArgs is premain function to the process parameters, accompanying
"-javaagent"came together. And the main function is different, this parameter is a string rather than a string array, if the parameters of a number of procedures, procedures that will be self-analytical string.Inst is a java.lang.instrument.Instrumentation examples from JVM automatically imported. Java.lang.instrument.Instrumentation instrument package is the definition of an interface, is the core part of this package, which concentrated almost all of the features, for example, the definition of type conversion and operation, and so on.
- Jar file packing
This Java class will be packaged into a jar file, and in which the properties are manifest by adding "Premain-Class" to a specified steps that are prepared with premain the Java class. (May also need to specify other properties to open more features)
- Operation
Running by the following Instrumentation with the Java programs:
Java-javaagent: jar document position [= imported premain parameters]
Java class files on the operation, can be understood as a byte array operations (such document will be binary-byte read a byte array). Developers can "ClassFileTransformer" transform methods which have, operation and eventually return to the definition of a class (a byte array). This regard, the BCEL Apache open source projects provide strong support, readers can reference in the article "Java SE 5 of Instrumentation practice," to see a BCEL and Instrumentation with examples. Specific bytecode operation is not the focus of this paper, therefore, in this paper, the example cited, but the type of a simple way to replace the use of Instrumentation demonstration.
Below, we have adopted a simple example to illustrate the basic use of Instrumentation.
First, we have a simple category, TransClass, via a static method returns an integer 1.
Public class TransClass (public int getNumber () (return 1;))
We run the following categories, the output can be "1."
Public class TestMainInJar (public static void main (String [] args) (System.out.println (new TransClass (). GetNumber ());))
Then, we will TransClass into the getNumber method as follows:
Public int getNumber () (return 2;)
The two then returned to the document compiled into Java class files, in order to distinguish between the return of an original class, we will return 2 of this type of document named TransClass2.class.2.
Next, we build a Transformer categories:
Import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.security . ProtectionDomain; class Transformer implements ClassFileTransformer (public static final String classNumberReturns2 = "TransClass.class.2" public static byte [] getBytesFromFile (String fileName) (try (/ / precondition File file = new File (fileName); InputStream is = new FileInputStream (file); file.length long length = (); byte [] bytes = new byte [(int) length]; / / Read in the bytes int offset = 0; int numRead = 0; while (offset <bytes . length & & (numRead = is.read (bytes, offset, bytes.length - offset))> = 0) (offset + = numRead;) if (offset <bytes.length) (throw new IOException ( "Could not completely read file "+ file.getName ());) is.close (); return bytes;) catch (Exception e) (System.out.println (" error occurs in _ClassTransformer! "+ e.getClass (). getName () ); return null;)) public byte [] transform (ClassLoader l, String className, Class <?> c, ProtectionDomain pd, byte [] b) throws IllegalClassFormatException (if (! className.equals ( "TransClass")) (return null;) return getBytesFromFile (classNumberReturns2);))
This class has ClassFileTransformer interface. Among them, according to the file name getBytesFromFile method read binary character stream, which provides the ClassFileTransformer transform method is completed replacement of the definition of conversion.
Finally, we have established a Premain categories, the agent into the Instrumentation premain methods:
Public class Premain (public static void premain (String agentArgs, Instrumentation inst) throws ClassNotFoundException, UnmodifiableClassException (inst.addTransformer (new Transformer ());))
Can be seen, addTransformer methods and does not specify which type to convert. Premain function in the conversion occurred after the implementation, before the implementation of main function, when a load of each category, will transform the operational methods, and see whether they need to change it, transform (Transformer category) methods, and procedures used className.equals ( "TransClass") to determine the need for the current type conversion.
Upon completion of the code, we will pack them for TestInstrument1.jar. 1 TransClass return to the types of documents that remain in the jar package, and returned to the 2 that TransClass.class.2 jar is put outside. Add the following inside the manifest attribute to specify where the premain categories:
Manifest-Version: 1.0 Premain-Class: Premain
In the running of this process, if we use ordinary run this way jar in the main function, the output can be "1." If running with the following:
Java-javaagent: TestInstrument1.jar-cp TestInstrument1.jar TestMainInJar
Output will be "2."
Of course, the main function of operating procedures do not necessarily need to be here, on this jar premain documents inside, here for just examples of procedures and on the convenience of packaged together.
In addition to using addTransformer way Instrumentation There is also another method "redefineClasses" for the realization of the designated premain conversion. Usage of similar, as follows:
Public class Premain (public static void premain (String agentArgs, Instrumentation inst) throws ClassNotFoundException, UnmodifiableClassException ClassDefinition def = (new ClassDefinition (TransClass.class, Transformer. GetBytesFromFile (Transformer.classNumberReturns2)); inst.redefineClasses (new ClassDefinition [] (def )); System.out.println ( "success");))
RedefineClasses function comparatively strong, can batch convert many types.
![]()
![]()
![]()
Java SE 6 new reading of the complete list of series of articles, the understanding of Java SE 6 other important enhancements.
ruihu@cn.ibm.com.

Lu:jing of computer science, open source software, and new things all have a deep interest.






