Simon Shkolnik
Simon Shkolnik

Reputation: 398

Using the attach api in 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.

Upvotes: 3

Views: 2160

Answers (2)

DuncG
DuncG

Reputation: 15136

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

Upvotes: 3

JCWasmx86
JCWasmx86

Reputation: 3583

You have to import com.sun.tools.attach.<className> or com.sun.tools.attach.spi.<className>. There are not that many resources, but this one from oracle seems like a good one: https://blogs.oracle.com/corejavatechtips/the-attach-api

Upvotes: 0

Related Questions