Compiling a class using Java code using a process

I have this piece of code that compiles a class called tspClassName when I compile with this code:

           Process compileProc = null;
        try {
            compileProc = Runtime.getRuntime().exec("javac -classpath ."
                       + File.separator + "src" + File.separator
                       + File.separator + "generated." + tspClassName + ".java -d ." + File.separator + "bin");
        // catch exception
           if (compileProc.exitValue() != 0) 
           {
               System.out.println("Compile exit status: "
                          + compileProc.exitValue());
                      System.err.println("Compile error:" +
                              compileProc.getErrorStream());

he displays this: "Compile exit status: 2 Compilation error: java.io.FileInputStream@17182c1 " The tspClassName.java class compiles without errors otherwise, so I assume it has to do with this path, and in my eclipse project tspClassName .java is in the package4.generated home task inside src, is there something wrong with the path I use in the code?

thank

0
source share
6 answers

Java , :

javac -classpath ./src//generated.ClassName.java -d ./bin

, . , Java-, - :

javac -classpath . src/generated/ClassName.java -d ./bin
                  ^

( "." ).

+1

, javax.tools API, :

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler()

:

0

- :

    String command = String.format(
        "javac -classpath . src%1$sgenerated%1$s%2$s.java -d .%1$sbin",
        File.separator,
        tspClassName
    );
    LOG("Executing " + command);
    //... exec(command) etc

... LOG - , , . , , , , .

, replace

    String command =
        "javac -classpath . src/generated/ClassName.java -d ./bin"
        .replace("/", File.separator)
        .replace("ClassName", tspClassName);

, , .


Process

OP , waitFor() . , / javac.

API:

, , .

Process.getOutputStream() et.al.

.

  • Java Puzzlers, 82:

0

exec() 3 , , ,

6 8 http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html

 Process compile = Runtime.getRuntime().exec("javac "+fname,null,new File(dir));
0

-, apache exec library, . Apache exec .

-, STD- std- , . , .

-, cmd, . cmd . .

And finally, if your goal is to simply compile the class / generate or modify the class file at runtime, give this a good read and try. He also has examples. You can also try libraries for generating code / manipulation classes such as BCEL, JavaAssist, etc.

Good luck.

0
source

Source: https://habr.com/ru/post/1756520/


All Articles