Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/external/source/msfJavaToolkit/javaCompile/CompileSourceInMemory.java
Views: 11779
// Based on the example from http://www.java2s.com/Code/Java/JDK-6/CompilingfromMemory.htm12package javaCompile;34import java.net.URI;5import java.util.Arrays;6import java.util.List;7import java.util.ArrayList;8import java.lang.String;910import javax.tools.JavaCompiler;11import javax.tools.JavaFileObject;12import javax.tools.SimpleJavaFileObject;13import javax.tools.StandardJavaFileManager;14import javax.tools.ToolProvider;15import javax.tools.JavaFileObject.Kind;1617public class CompileSourceInMemory {1819public static boolean CompileFromMemory(String strClass, String strCodeContent) {20String[] classNames = { strClass };21String[] codeContent = { strCodeContent };22return CompileFromMemory(classNames, codeContent, null);23}2425public static boolean CompileFromMemory(String[] classNames, String[] codeContent) {26return CompileFromMemory(classNames, codeContent, null);27}2829public static boolean CompileFromMemory(String[] classNames, String[] codeContent, String[] compOptions) {3031List<String> compOptList = null;32if (compOptions != null) { compOptList = Arrays.asList(compOptions); }3334JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();3536// Need to add a check that classNames.length == codeContent.length, else we're fubared.37List<JavaFileObject> files = new ArrayList<JavaFileObject> () ;38int i = 0;39for (String codePage : codeContent) {40files.add(new JavaSourceFromString(classNames[i], codePage));41i++;42}4344Iterable<? extends JavaFileObject> compilationUnits = files;4546JavaCompiler.CompilationTask task = compiler.getTask(null, null, null, compOptList, null, compilationUnits);4748boolean success = task.call();4950return success;5152}53}5455class JavaSourceFromString extends SimpleJavaFileObject {56final String code;5758JavaSourceFromString(String name, String code) {59super(URI.create("string:///" + name.replace('.','/') + Kind.SOURCE.extension),Kind.SOURCE);60this.code = code;61}6263@Override64public CharSequence getCharContent(boolean ignoreEncodingErrors) {65return code;66}67}68697071