Java Instrumentation — A Simple Working Example in Java

Exploring the Advanced Features in Java

Ruby Valappil
Javarevisited

--

Photo by Boitumelo Phetla on Unsplash

In this article, we will explore how to instrument a Java program.

Java package that provides services to allow instrumentation is java.lang.instrument.

What is Instrumentation?

From the docs — “The mechanism for instrumentation is modification of the byte-codes of methods.”

In simple words, we know that when we run our Java programs it gets converted to bytecode. These are then loaded to JVM using classloaders. Using Instrumentation APIs we get to modify the bytecodes of these programs at runtime.

Application monitoring tools use this same service to provide useful information on execution time etc.

The class that intercepts the bytecode is called an Agent Class.

Know the Components

The main components are,

1. Agent Class — It’s similar to the main class of a Java application. This class must contain a method named premain().
premain() method can have one of two possible signatures,

From the docs-
public static void premain(String agentArgs, Instrumentation inst);
public static

--

--