IntelliJ IDEA - Java instrumentation premain gets called twice when directly run inside IDE

das Keks :

For some reason the premain of my Java Agent is executed twice when I run a program inside of IDEA and add the Agent jar via the IDEA VM options:

I have the following sample program and added the Java Agent in IDEA via
Run Configuration -> VM options: -javaagent:/path/to/agent/MyJavaAgent.jar

package com.example;

public class Test {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

The MyJavaAgent.jar has the following structure:

.
├── com
│   └── example
│       └── MyJavaAgent.class
└── META-INF
    └── MANIFEST.MF

MyJavaAgent.java

package com.example;

import java.lang.instrument.Instrumentation;

public class MyJavaAgent {
    private static int callCount = 0;
    public static void premain(String agentArgs, Instrumentation inst) {
        callCount++;
        System.out.println("premain call " + callCount);
    }
}

MANIFEST.MF

Manifest-Version: 1.0
Premain-Class: com.example.MyJavaAgent
Can-Redefine-Classes: true
Can-Retransform-Classes: true
Can-Set-Native-Method-Prefix: true

When I run the sample Test.main() I get the following output:

> Task :Test.main()
premain call 1
premain call 2
Hello World!

When I run the program without IDEA everything looks like expected:

> java -javaagent:/path/to/agent/MyJavaAgent.jar com.example.Test
premain call 1
Hello World!

Can someone explain what is happening here? Is that an IDEA bug?

I'm using IntelliJ IDEA 2019.3.4 (Ultimate Edition), Build #UI-193.6911.18

CrazyCoder :

It appears to be related to how IntelliJ IDEA is starting your class via Gradle by generating the task on the fly.

The workaround is to disable the run delegation to Gradle.

I've reported a bug that you can follow for updates.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=360134&siteId=1