Skip to content

Commit 535760d

Browse files
committed
Add compile(Reader) method
JavaEngine provides the possibility to evaluate Java code from a Reader, sometimes one might not want to have that code immediately executed. For a Java File, the compile(File,Writer) method was provided already, this commit adds such a method for compiling from Reader.
1 parent 1c965a1 commit 535760d

File tree

1 file changed

+29
-4
lines changed

1 file changed

+29
-4
lines changed

src/main/java/org/scijava/plugins/scripting/java/JavaEngine.java

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@
9090
* </p>
9191
*
9292
* @author Johannes Schindelin
93+
* @author Jonathan Hale
9394
*/
9495
public class JavaEngine extends AbstractScriptEngine {
9596

@@ -141,6 +142,31 @@ public Object eval(String script) throws ScriptException {
141142
*/
142143
@Override
143144
public Object eval(Reader reader) throws ScriptException {
145+
final Writer writer = getContext().getErrorWriter();
146+
try {
147+
final Class<?> clazz = compile(reader);
148+
javaService.run(clazz);
149+
} catch (Exception e) {
150+
if (writer != null) {
151+
final PrintWriter err = new PrintWriter(writer);
152+
e.printStackTrace(err);
153+
err.flush();
154+
} else {
155+
if (e instanceof ScriptException)
156+
throw (ScriptException) e;
157+
throw new ScriptException(e);
158+
}
159+
}
160+
return null;
161+
}
162+
163+
/**
164+
* Compiles and runs the specified {@code .java} class.
165+
*
166+
* @param reader the reader producing the source code for a Java class
167+
* @returns the compiled Java class as {@link Class}.
168+
*/
169+
public Class<?> compile(Reader reader) throws ScriptException {
144170
final String path = (String)get(FILENAME);
145171
File file = path == null ? null : new File(path);
146172

@@ -170,12 +196,11 @@ public Object eval(Reader reader) throws ScriptException {
170196
URLClassLoader classLoader = new URLClassLoader(urls,
171197
Thread.currentThread().getContextClassLoader());
172198

173-
// needed for sezpoz
199+
// needed for annotation processing
174200
Thread.currentThread().setContextClassLoader(classLoader);
175201

176-
// launch main class
177-
final Class<?> clazz = classLoader.loadClass(mainClass);
178-
javaService.run(clazz);
202+
// load main class
203+
return classLoader.loadClass(mainClass);
179204
} finally {
180205
builder.cleanup();
181206
}

0 commit comments

Comments
 (0)