'Specifying a javaagent within the jar file to be run

I'm developing an OpenJPA application (no webserver, regular java se app). In order to make OpenJPA work with my application, I need to set the openjpa-all-2.3.0.jar as a javaagent.

java -cp ... -javaagent:/full/path/to/openjpa-all-2.3.0.jar -jar app.jar

As I am packaging the openjpa.jar within the app.jar anyway, I am now wondering how it is possible to specify the javaagent, as a jar within my application jar file.

This didn't work

java -cp ".;.\app.jar" -javaagent:openjpa-all-2.3.0.jar pckg.Main


Solution 1:[1]

There's no way to do it. The JVM does not look at the classpath to find the specified agent; it is expecting a file path, and you also cannot specify file paths inside jar files.

JDK-4648386 is the related feature request, and was closed Won't Fix after 18 years.

However, what you can do is write code to copy the agent jar from a classpath resource to a temporary file, and then attach it to the current running JVM. The ByteBuddy Agent library provides tooling to do this.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1