How to Use NetBeans to Create a Java Agent for Bytecode Modification

A Java agent can inspect or change compiled classes as the JVM loads them. This makes it useful for tracing method calls, measuring performance, enforcing rules, and adding diagnostics without editing every source file. NetBeans provides a convenient workspace for creating the agent, testing it against a sample application, and examining generated bytecode.

The core API is java.lang.instrument.Instrumentation. A premain agent is loaded at JVM startup, while an attach agent connects to an already running process. This guide uses a premain agent because it is straightforward to configure in NetBeans and suitable for repeatable development tests.

Bytecode modification should be treated as production infrastructure rather than a casual replacement for application code. Australian teams working in Sydney, Melbourne, Brisbane, or Perth may need to consider personal information, customer consent, and the Privacy Act 1988 when instrumentation records request data or user identifiers.

Understand The Agent Lifecycle

The JVM looks for a manifest entry named Premain-Class when an agent is supplied with the -javaagent option. It then calls a method such as premain(String arguments, Instrumentation instrumentation) before the application’s main method begins.

The agent registers a ClassFileTransformer. For each eligible class, the transformer receives the original class bytes and may return new bytes. Returning null leaves the class unchanged. A transformer should filter aggressively, because changing JDK classes, framework internals, or the agent’s own classes can cause recursion and class-loading failures.

A simple design separates the agent from the application being observed. Put the agent in its own Maven or Gradle project, then create a small target application in a second NetBeans project. This arrangement makes class paths, debugging, and packaging easier to understand.

Create The NetBeans Project

In NetBeans, create a Java Application or Maven project named something like TracingAgent. Add an Agent package and create TracingAgent.java. For a Maven build, use the Maven Shade Plugin or the standard JAR Plugin to add the required manifest entry.

Useful project components include:

  • An agent class containing premain
  • A transformer class implementing ClassFileTransformer
  • ASM or Byte Buddy as a bytecode library
  • A separate sample application for repeatable tests

For a first experiment, Byte Buddy offers a readable API and handles much of the difficult bytecode validation. ASM provides finer control and a smaller conceptual distance from class-file instructions, although it requires careful stack-map and descriptor management. Choose one library rather than mixing transformation models in the initial project.

NetBeans can download dependencies through Maven, show compiler errors in the editor, and attach a debugger to the sample application. Set the project’s Java platform to the same JDK used for execution; a mismatch between compilation and runtime versions often creates confusing class-file errors.

Add A Premain Entry Point

The following agent logs the loading of application classes. The filter avoids modifying the agent itself and ignores common platform packages:

package example.agent;

import java.lang.instrument.Instrumentation;

public final class TracingAgent {
    private TracingAgent() {
    }

    public static void premain(String args, Instrumentation instrumentation) {
        instrumentation.addTransformer(new MethodTransformer(), false);
        System.out.println("Tracing agent active: " + args);
    }
}

A transformer can initially return null while you verify that the agent starts correctly:

package example.agent;

import java.lang.instrument.ClassFileTransformer;
import java.security.ProtectionDomain;

public final class MethodTransformer implements ClassFileTransformer {
    @Override
    public byte[] transform(Module module, ClassLoader loader,
            String className, Class<?> classBeingRedefined,
            ProtectionDomain protectionDomain, byte[] classfileBuffer) {

        if (className == null
                || className.startsWith("java/")
                || className.startsWith("sun/")
                || className.startsWith("example/agent/")) {
            return null;
        }

        System.out.println("Observed: " + className);
        return null;
    }
}

This first stage confirms the JVM option, manifest, and class path before any bytecode is changed. Once it works, replace the final return null with a Byte Buddy or ASM transformation that adds timing, logging, or another narrowly defined behaviour.

Package The Agent Correctly

The JAR manifest must identify the entry point. In a Maven build, the essential configuration resembles this:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-jar-plugin</artifactId>
  <configuration>
    <archive>
      <manifestEntries>
        <Premain-Class>example.agent.TracingAgent</Premain-Class>
        <Can-Redefine-Classes>true</Can-Redefine-Classes>
        <Can-Retransform-Classes>true</Can-Retransform-Classes>
      </manifestEntries>
    </archive>
  </configuration>
</plugin>

Build the project with NetBeans or mvn package, then launch the target application using the absolute path to the agent JAR:

java -javaagent:/path/to/TracingAgent.jar=dev \
     -cp target/sample-app.jar example.app.Main

On Windows, quote paths containing spaces. On macOS and Linux, confirm that the agent’s dependency JARs are included in the final artifact; a manifest pointing to a class that is absent from the runtime class path will produce an agent startup error.

Transform Classes With Care

A useful transformer modifies only application packages, such as au.example.orders, and excludes generated proxies, test fixtures, and synthetic classes where possible. With Byte Buddy, method entry and exit advice can be applied to selected methods without manually editing instruction offsets. With ASM, use a ClassReader, a ClassWriter, and a visitor that targets named methods.

Keep transformations deterministic and idempotent. If a class can be retransformed, applying the same advice twice may duplicate logging or corrupt the intended control flow. Always preserve exception paths and return values, and test constructors, overloaded methods, interfaces, lambdas, and asynchronous callbacks separately.

Static analysis is valuable before runtime testing; the NetBeans workflow for SpotBugs analysis can help identify unsafe code around the agent and its sample application. In particular, inspect:

  • Class-loader assumptions
  • Thread-safety of shared counters
  • Exception handling inside transformed methods
  • Logging of request or customer information

Run And Debug The Sample

Create a small target class with methods that can be called repeatedly. In NetBeans, place the -javaagent option in the project’s Run configuration, not among ordinary application arguments. Set breakpoints in premain and transform, then watch the className, loader, and byte-array length.

For performance work, record timestamps with a monotonic clock such as System.nanoTime() rather than wall-clock time. Exporting raw HTTP response information for analysis can be useful; a related frequency visualisation script demonstrates how request outcomes can later be summarised. Avoid placing full URLs, authentication headers, or personal data in agent logs.

When instrumenting Java EE or Jakarta EE applications, test container-managed boundaries carefully. A transformed EJB method may run through a proxy, interceptor, or transaction context rather than as a direct Java call; background work may also execute on a different thread. A stateful session bean example provides useful context when checking how lifecycle and invocation behaviour affect observations.

Compare Implementation Choices

The right approach depends on whether the agent is a learning exercise, a controlled diagnostic tool, or a long-lived observability component. NetBeans is especially helpful when each option is kept in a separate sample project and tested against the same target classes.

Approach Strength Main risk Suitable starting use
Plain Instrumentation Minimal dependencies and clear JVM lifecycle Manual bytecode work Logging loaded classes
ASM Precise instruction-level control Stack-map and descriptor errors Small, specialised transformations
Byte Buddy Readable rules and mature method advice Additional dependency and abstraction Timing and method tracing
Attach API Connects to an existing JVM Permissions and operational complexity Controlled diagnostics

Before deployment, check the target JDK version, framework proxies, module access, startup time, and log volume. For an Australian production environment, retain only the information needed for the stated purpose, restrict access to diagnostic output, and review whether Privacy Act obligations apply when traces can identify customers or employees. A small, reversible transformation is easier to operate than a broad agent that changes every loaded class.