Search code examples
javajvmclassloaderbytecode

Limits and scope of the Java Attach API


As far as I understand the Attach API introduced in Java 6 allows inter-process modification of classes running in a target JVM by means of agents. My questions are:

  1. Is this strategy limited to only the instrumentation of classes that have NOT been loaded yet by the target JVM ? and
  2. Which are the limits of these transformations ?. For example, only the body of existing methods can be modified ?, or everything in the class definition could be changed ?

Solution

    1. You can instrument both classes already loaded or to be loaded by intercepting them with a ClassFileTransformer. However if a retransformed method has active stack frames, those active frames continue to run the bytecodes of the original method. The retransformed method will be used on new invokes.
    2. The redefinition/retransformation may change method bodies, the constant pool and attributes. The redefinition/retransformation must not add, remove or rename fields or methods, change the signatures of methods, or change inheritance. These restrictions maybe be lifted in future versions. The class file bytes are not checked, verified and installed until after the transformations have been applied, if the resultant bytes are in error this method will throw an exception.

    The javadoc for the Instrumentation interface contains most of the information you are asking about.