Java Code Examples for javax.tools.JavaCompiler#run()

The following examples show how to use javax.tools.JavaCompiler#run() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
static void createTestClass() throws IOException {
    FileOutputStream fos = new FileOutputStream(TESTFILE + ".java");
    PrintStream ps = new PrintStream(fos);
    ps.println("public class " + TESTFILE + "{");
    ps.println("public static void main(String[] args) {\n");
    ps.println("System.out.println(System.getProperty(\"sun.boot.library.path\"));\n");
    ps.println("}}\n");
    ps.close();
    fos.close();

    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    String javacOpts[] = {TESTFILE + ".java"};
    if (javac.run(null, null, null,  javacOpts) != 0) {
        throw new RuntimeException("compilation of " + TESTFILE + ".java Failed");
    }
}
 
Example 2
static void createTestClass() throws IOException {
    FileOutputStream fos = new FileOutputStream(TESTFILE + ".java");
    PrintStream ps = new PrintStream(fos);
    ps.println("public class " + TESTFILE + "{");
    ps.println("public static void main(String[] args) {\n");
    ps.println("System.out.println(System.getProperty(\"sun.boot.library.path\"));\n");
    ps.println("}}\n");
    ps.close();
    fos.close();

    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    String javacOpts[] = {TESTFILE + ".java"};
    if (javac.run(null, null, null,  javacOpts) != 0) {
        throw new RuntimeException("compilation of " + TESTFILE + ".java Failed");
    }
}
 
Example 3
static void createTestClass() throws IOException {
    FileOutputStream fos = new FileOutputStream(TESTFILE + ".java");
    PrintStream ps = new PrintStream(fos);
    ps.println("public class " + TESTFILE + "{");
    ps.println("public static void main(String[] args) {\n");
    ps.println("System.out.println(System.getProperty(\"sun.boot.library.path\"));\n");
    ps.println("}}\n");
    ps.close();
    fos.close();

    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    String javacOpts[] = {TESTFILE + ".java"};
    if (javac.run(null, null, null,  javacOpts) != 0) {
        throw new RuntimeException("compilation of " + TESTFILE + ".java Failed");
    }
}
 
Example 4
Source Project: rocketmq   File: DynaCode.java    License: Apache License 2.0 5 votes vote down vote up
private void compile(String[] srcFiles) throws Exception {
    String args[] = this.buildCompileJavacArgs(srcFiles);
    ByteArrayOutputStream err = new ByteArrayOutputStream();
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new NullPointerException(
                "ToolProvider.getSystemJavaCompiler() return null,please use JDK replace JRE!");
    }
    int resultCode = compiler.run(null, null, err, args);
    if (resultCode != 0) {
        throw new Exception(err.toString(RemotingHelper.DEFAULT_CHARSET));
    }
}
 
Example 5
Source Project: rocketmq_trans_message   File: DynaCode.java    License: Apache License 2.0 5 votes vote down vote up
private void compile(String[] srcFiles) throws Exception {
    String args[] = this.buildCompileJavacArgs(srcFiles);
    ByteArrayOutputStream err = new ByteArrayOutputStream();
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new NullPointerException(
            "ToolProvider.getSystemJavaCompiler() return null,please use JDK replace JRE!");
    }
    int resultCode = compiler.run(null, null, err, args);
    if (resultCode != 0) {
        throw new Exception(err.toString(RemotingHelper.DEFAULT_CHARSET));
    }
}
 
Example 6
public static void main(String[] args) {
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    javac.run(System.in, null, null,
              "-Xprint",
              "com.sun.tools.javac.code.Types",
              "com.sun.tools.javac.parser.Parser",
              "java.util.EnumSet");
}
 
Example 7
@SuppressWarnings("unchecked")
protected Class<FastDeserializer<T>> compileClass(final String className) throws IOException,
        ClassNotFoundException {
    final OutputStream infoLoggingStream = LoggingOutputStream.infoLoggingStream(LOGGER);
    final OutputStream errorLoggingStream = LoggingOutputStream.errorLoggingStream(LOGGER);
    codeModel.build(destination, new PrintStream(infoLoggingStream));

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new FastDeserializerGeneratorException("no system java compiler is available");
    }

    int compileResult;
    if (compileClassPath != null) {
        compileResult = compiler.run(
                null,
                infoLoggingStream,
                errorLoggingStream,
                "-cp",
                compileClassPath,
                destination.getAbsolutePath() + GENERATED_SOURCES_PATH + className + ".java"
        );
    } else {
        compileResult = compiler.run(
                null,
                infoLoggingStream,
                errorLoggingStream,
                destination.getAbsolutePath() + GENERATED_SOURCES_PATH + className + ".java");
    }

    if (compileResult != 0) {
        throw new FastDeserializerGeneratorException("unable to compile: " + className);
    }

    return (Class<FastDeserializer<T>>) classLoader.loadClass(GENERATED_PACKAGE_NAME + "."
            + className);
}
 
Example 8
private void compile(String[] srcFiles) throws Exception {
    String args[] = this.buildCompileJavacArgs(srcFiles);
    ByteArrayOutputStream err = new ByteArrayOutputStream();
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new NullPointerException(
            "ToolProvider.getSystemJavaCompiler() return null,please use JDK replace JRE!");
    }
    int resultCode = compiler.run(null, null, err, args);
    if (resultCode != 0) {
        throw new Exception(err.toString(RemotingHelper.DEFAULT_CHARSET));
    }
}
 
Example 9
public static void main(String[] args) {
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    javac.run(System.in, null, null,
              "-Xprint",
              "com.sun.tools.javac.code.Types",
              "com.sun.tools.javac.parser.Parser",
              "java.util.EnumSet");
}
 
Example 10
Source Project: Concurnas   File: Javac.java    License: MIT License 5 votes vote down vote up
/**
 * Given a list of file-scope java code (equivalent to a .java file, including package and
 * import declarations), compile() invokes javac to compile them, produce classfiles and return
 * a list of <className, byte[]> pairs.
 * 
 * compile() dumps the source strings into their respective files, has javac compile them, then
 * reads back the equivalent class files. The name of the source file is gleaned from the string
 * itself; a string containing "public class Foo" is stored in tmpDir/Foo.java (where tmpDir is
 * a temporary directory that's deleted after the compilation), and if no public class or
 * interface is found, the name of the first class in the string is used.
 * 
 * Note that the list of returned classes may be larger than 
 * 
 * @param srcCodes
 *            . List of strings.
 * @return List<className,byte[]>. className is fully qualified, and byte[] contains the
 *         bytecode of the class.
 * @throws IOException
 */
public static List<ClassInfo> compile(List<String> srcCodes) throws IOException {

    List<SourceInfo> srcInfos = getSourceInfos(srcCodes);

    File rootDir = getTmpDir(); // something like "/tmp/kilim$2348983948"

    File classDir = new File(rootDir.getAbsolutePath() + File.separatorChar + "classes");
    classDir.mkdir(); // "<rootDir>/classes"

    String options[] = { "-d", classDir.getAbsolutePath() };

    String args[] = new String[options.length + srcCodes.size()];
    System.arraycopy(options, 0, args, 0, options.length);
    int i = options.length;

    for (SourceInfo srci : srcInfos) {
        String name = rootDir.getAbsolutePath() + File.separatorChar + srci.className + ".java";
        writeFile(new File(name), srci.srcCode.getBytes());
        args[i++] = name;
    }

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    compiler.run(null, null, null, args);

    List<ClassInfo> ret = new ArrayList<ClassInfo>();
    addClasses(ret, "", classDir);
    deleteDir(rootDir);
    return ret;
}
 
Example 11
Source Project: jdk8u60   File: Xprint.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    javac.run(System.in, null, null,
              "-Xprint",
              "com.sun.tools.javac.code.Types",
              "com.sun.tools.javac.parser.Parser",
              "java.util.EnumSet");
}
 
Example 12
Source Project: learnjavabug   File: ByJavaCompiler.java    License: MIT License 5 votes vote down vote up
public static void c() {
    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
    int compilationResult = javaCompiler.run(null, null, null, "-cp", "/tmp/ccc/CCC.jar", "/tmp/Main.java");
    // 返回0表示编译成功
    if (compilationResult == 0) {
        System.out.println("success");
    } else {
        System.out.println("fail");
    }
}
 
Example 13
Source Project: rocketmq   File: DynaCode.java    License: Apache License 2.0 5 votes vote down vote up
private void compile(String[] srcFiles) throws Exception {
    String args[] = this.buildCompileJavacArgs(srcFiles);
    ByteArrayOutputStream err = new ByteArrayOutputStream();
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new NullPointerException(
            "ToolProvider.getSystemJavaCompiler() return null,please use JDK replace JRE!");
    }
    int resultCode = compiler.run(null, null, err, args);
    if (resultCode != 0) {
        throw new Exception(err.toString(RemotingHelper.DEFAULT_CHARSET));
    }
}
 
Example 14
@SuppressWarnings("unchecked")
protected Class compileClass(final String className, Set<String> knownUsedFullyQualifiedClassNameSet)
    throws IOException, ClassNotFoundException {
  codeModel.build(destination);

  String filePath = destination.getAbsolutePath() + generatedSourcesPath + className + ".java";
  LOGGER.info("Generated source file: " + filePath);

  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  String compileClassPathForCurrentFile = Utils.inferCompileDependencies(compileClassPath, filePath, knownUsedFullyQualifiedClassNameSet);
  LOGGER.info("For source file: " + filePath + ", and the inferred compile class path: " + compileClassPathForCurrentFile);
  int compileResult;
  try {
    /*
     * Disable sharedNameTable in runtime complication
     *
     * The SharedNameTable was introduced to speed up Java complication by using soft references
     * to avoid re-allocations. However, in fast-avro runtime compilation, sharedNameTable brings
     * severe Memory and GC issue. When fast-avro needed to process a large number of different
     * schemas, SharedNameTable objects will consume huge memory and cannot be freed.
     *
     * SharedNameTable should be disabled for runtime compilation by “-XDuseUnsharedTable” config.
     * The memory issue by SharedNameTable does not exist in Java 11 (tested JDK-11_0_5-zulu
     * and JDK-11_0_5-zing_19_12_100_0_1), thus the change can be reverted in java 11.
     * Keeping this config also does not bring any downgrade.
     *
     */
    compileResult = compiler.run(null, null, null, "-cp", compileClassPathForCurrentFile, filePath, "-XDuseUnsharedTable");
  } catch (Exception e) {
    throw new FastSerdeGeneratorException("Unable to compile:" + className, e);
  }

  if (compileResult != 0) {
    throw new FastSerdeGeneratorException("Unable to compile:" + className);
  }

  return classLoader.loadClass(generatedPackageName + "." + className);
}
 
Example 15
public static void main(String[] args) {
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    javac.run(System.in, null, null,
              "-Xprint",
              "com.sun.tools.javac.code.Types",
              "com.sun.tools.javac.parser.Parser",
              "java.util.EnumSet");
}
 
Example 16
@SuppressWarnings("unchecked")
protected Class<FastSerializer<T>> compileClass(final String className) throws IOException,
        ClassNotFoundException {
    final OutputStream infoLoggingStream = LoggingOutputStream.infoLoggingStream(LOGGER);
    final OutputStream errorLoggingStream = LoggingOutputStream.errorLoggingStream(LOGGER);
    codeModel.build(destination, new PrintStream(infoLoggingStream));

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new FastSerializerGeneratorException("no system java compiler is available");
    }

    int compileResult;
    if (compileClassPath != null) {
        compileResult = compiler.run(
                null,
                infoLoggingStream,
                errorLoggingStream,
                "-cp",
                compileClassPath,
                destination.getAbsolutePath() + GENERATED_SOURCES_PATH + className + ".java"
        );
    } else {
        compileResult = compiler.run(
                null,
                infoLoggingStream,
                errorLoggingStream,
                destination.getAbsolutePath() + GENERATED_SOURCES_PATH + className + ".java");
    }

    if (compileResult != 0) {
        throw new FastSerializerGeneratorException("unable to compile: " + className);
    }

    return (Class<FastSerializer<T>>) classLoader.loadClass(GENERATED_PACKAGE_NAME + "."
            + className);
}
 
Example 17
public static void main(String[] args) {
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    javac.run(System.in, null, null,
              "-Xprint",
              "com.sun.tools.javac.code.Types",
              "com.sun.tools.javac.parser.Parser",
              "java.util.EnumSet");
}
 
Example 18
private static void compile(String path) {
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  StandardJavaFileManager fm = compiler.getStandardFileManager(diagnostic -> logger.error("{}, {}", diagnostic.getLineNumber(), diagnostic.getSource().toUri()), null, null);
  try {
    fm.setLocation(StandardLocation.CLASS_PATH, Lists.newArrayList(new File(System.getProperty("java.class.path"))));
  } catch (IOException e) {
    logger.error("Fail to set location for compiler file manager", e);
  }
  if (compiler.run(null, null, null, path) != 0) {
    ShutDownCenter.initShutDown(new InvalidConfigException());
  }
}
 
Example 19
Source Project: Flink-CEPplus   File: ClassLoaderUtils.java    License: Apache License 2.0 4 votes vote down vote up
private static int compileClass(File sourceFile) {
	JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
	return compiler.run(null, null, null, "-proc:none", sourceFile.getPath());
}
 
Example 20
/**
 * Run the Java compiler.
 * (A JSR 199 implementation must be available.)
 * @param src a source root (runs javac on all *.java it finds matching {@code srcIncludes})
 * @param srcIncludes a pattern of source files names without path to compile (useful for testing incremental compiles), or null for all
 * @param dest a dest dir to compile classes to
 * @param cp classpath entries; if null, use Java classpath of test
 * @param source the source level option to the compiler
 * @param stderr output stream to print messages to, or null for test console (i.e. do not capture)
 * @return true if compilation succeeded, false if it failed
 */
public static boolean runJavac(File src, String srcIncludes, File dest, File[] cp, OutputStream stderr, String source) {
    List<String> args = new ArrayList<String>();
    args.add("-classpath");
    StringBuilder b = new StringBuilder(dest.getAbsolutePath());
    if (cp != null) {
        for (File entry : cp) {
            b.append(File.pathSeparatorChar);
            b.append(entry.getAbsolutePath());
        }
    } else {
        b.append(File.pathSeparatorChar).append(System.getProperty("java.class.path"));
    }
    args.add(b.toString());
    args.add("-d");
    args.add(dest.getAbsolutePath());
    args.add("-sourcepath");
    args.add(src.getAbsolutePath());
    args.add("-s");
    File destG = new File(dest.getParentFile(), "generated-" + dest.getName());
    args.add(destG.getAbsolutePath());
    args.add("-source");
    if (source == null) {
        args.add("6");
    } else {
        args.add(source);
    }
    args.add("-Xlint:-options");
    dest.mkdirs();
    destG.mkdirs();
    scan(args, src, srcIncludes);
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    Assert.assertNotNull(String.format(
            "No JSR 199 compiler impl found; perhaps tools.jar missing from CP? BootClassPath: %s. ClassPath: %s",
            System.getProperty("sun.boot.class.path"),  //NOI18N
            System.getProperty("java.class.path")       //NOI18N
            ),
        compiler);
    //System.err.println("running javac with args: " + args);
    return compiler.run(null, null, stderr, args.toArray(new String[args.size()])) == 0;
}