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

The following examples show how to use javax.tools.JavaCompiler#run() . 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
Source File: TestBootNativeLibraryPath.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
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
Source File: TestBootNativeLibraryPath.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
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
Source File: TestBootNativeLibraryPath.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
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 File: Xprint.java    From jdk8u60 with 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 5
Source File: JavaMethod.java    From syncer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 6
Source File: Xprint.java    From openjdk-jdk8u with 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 7
Source File: FastSerializerGeneratorBase.java    From avro-fastserde with Apache License 2.0 5 votes vote down vote up
@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 8
Source File: Xprint.java    From openjdk-jdk8u-backup with 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 9
Source File: FastSerdeBase.java    From avro-util with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@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 10
Source File: DynaCode.java    From rocketmq with 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 11
Source File: ByJavaCompiler.java    From learnjavabug with 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 12
Source File: DynaCode.java    From rocketmq with 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 13
Source File: Javac.java    From Concurnas with 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 14
Source File: Xprint.java    From TencentKona-8 with 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 15
Source File: DynaCode.java    From rocketmq-all-4.1.0-incubating with 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 16
Source File: FastDeserializerGeneratorBase.java    From avro-fastserde with Apache License 2.0 5 votes vote down vote up
@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 17
Source File: Xprint.java    From openjdk-jdk9 with 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 18
Source File: DynaCode.java    From rocketmq_trans_message with 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 19
Source File: AnnotationProcessorTestUtils.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * 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;
}
 
Example 20
Source File: ClassLoaderUtils.java    From Flink-CEPplus with 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());
}