Search code examples
javaprocessbuilderjavaagents

-javaagent: option recognised as a command


In an application I am writing, I need to use the javaagent option to call an external jar in the same folder as my current jar file. When I run the code from the jar file, I get told: "Error: Could not find or load main class -javaagent:" but when I am running it from a batch file, it works as excepted.

I am using a ProcessBuilder to start the application:

String java = System.getProperty("java.home") + File.separatorChar + "bin" + File.separatorChar +"java.exe";
File transagent = new File(pluginDir + File.separatorChar + "TransAgent.jar");
String doublequote = String.valueOf('"');
List<String> commandlist = new ArrayList<String>();
commandlist.add(java);
commandlist.add(" -javaagent:");
commandlist.add(doublequote);
commandlist.add(transagent.getAbsolutePath());
commandlist.add(doublequote);
for(int i = 0; i < commandlist.size(); i++){
    String part = commandlist.get(i);
    System.out.print(part);
}
System.out.println();
ProcessBuilder pb = new ProcessBuilder();
pb.command(commandlist);
pb.redirectError(Redirect.appendTo(errorfile));
pb.redirectOutput(Redirect.appendTo(logfile));
try {
    pb.start();
} catch (IOException e) {
    e.printStackTrace();
}

But, when I go to the error file, I see "Error: Could not find or load main class -javaagent:"

This would usually be thrown if the option isn't valid, but I've checked the dash to work file. And I put what printed from the application in a batch file, and it worked fine. Why?


Solution

  • You can try this code below:

        ProcessBuilder pb = new ProcessBuilder("java", "-javaagent:"+transagent.getAbsolutePath(), "YouMainClass");
        pb.redirectError(Redirect.appendTo(errorfile));
        pb.redirectOutput(Redirect.appendTo(logfile));
    
        try
        {
            pb.start();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }