Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the attach api in Java

Tags:

java

I want to use the attach API in Java 14. To my knowledge, that was moved to jdk.attach in Java 9. I ran java --list-modules and I had the module installed.

How do I actually use the module in my project? I tried import jdk.attach but that threw an error.

like image 924
Simon Shkolnik Avatar asked Feb 18 '26 02:02

Simon Shkolnik


1 Answers

I use JDK14 with module definitions, this is all I needed to change to use with my module-info.java:

requires transitive jdk.attach;

Here is a simple call to run it:

import com.sun.tools.attach.VirtualMachine;

public class AttachApi {

    public static void main(String[] args) throws Exception {
        System.out.println("BEGIN");
        var vms = VirtualMachine.list();
        for (var vm : vms) {
            System.out.println("vm="+vm);
        }

        System.out.println("END");
    }
}

The above code runs as-is with a non-module project in newer JDK if saved to a file and compiled then run, or compiled+run in one step with java:

 %JAVA_HOME%\bin\java AttachApi.java
like image 148
DuncG Avatar answered Feb 19 '26 15:02

DuncG