I'm having problems dynamically compiling and loading classes when using the command mvn exec:java.
I created a small example based on this tutorial that works in IntelliJ but does not execute when executed through the command line.
Here is my class main:
public class Debug {
public static void main(String[] args) {
DynamicCompiler compiler = new DynamicCompiler();
SayHello hello = compiler.getHello();
hello.sayHello();
}
}
Interface SayHello:
public interface SayHello {
public void sayHello();
}
Grade DynamicCompiler:
import javax.tools.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.security.SecureClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class DynamicCompiler {
private final static String CLASS_PATH = "Hello";
private final static String SOURCE;
static {
StringBuilder builder = new StringBuilder();
builder.append("public class Hello implements SayHello {\n")
.append(" public void sayHello() {\n")
.append(" System.out.println(\"Hello World\")\n;")
.append(" }\n")
.append("}");
SOURCE = builder.toString();
}
public SayHello getHello() {
return compileAndLoadSource(SOURCE, CLASS_PATH);
}
private SayHello compileAndLoadSource(String src, String fullName) {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
JavaFileManager fileManager = new
ClassFileManager(compiler.getStandardFileManager(null, null, null));
List<JavaFileObject> jfiles = new ArrayList<JavaFileObject>();
jfiles.add(new CharSequenceJavaFileObject(fullName, src));
List<String> optionList = new ArrayList<String>();
DiagnosticCollector<JavaFileObject> diagnostics = new
DiagnosticCollector<JavaFileObject>();
JavaCompiler.CompilationTask task =
compiler.getTask(null, fileManager, diagnostics, optionList,
null, jfiles);
boolean success = task.call();
if (!success) {
System.out.println("UNSUCCESSFUL:");
for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
System.out.println(diagnostic.getCode());
System.out.println(diagnostic.getKind());
System.out.println(diagnostic.getPosition());
System.out.println(diagnostic.getStartPosition());
System.out.println(diagnostic.getEndPosition());
System.out.println(diagnostic.getSource());
System.out.println(diagnostic.getMessage(null));
}
return null;
}
try {
Object instance = fileManager.getClassLoader(null).loadClass(fullName).newInstance();
return (SayHello) instance;
} catch (InstantiationException e) {
e.printStackTrace();
return null;
} catch (IllegalAccessException e) {
e.printStackTrace();
return null;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
public static class JavaClassObject extends SimpleJavaFileObject {
protected final ByteArrayOutputStream bos = new ByteArrayOutputStream();
public JavaClassObject(String name, Kind kind) {
super(URI.create("string:///" + name.replace('.', '/') + kind.extension), kind);
}
public byte[] getBytes() {
return bos.toByteArray();
}
@Override
public OutputStream openOutputStream() throws IOException {
return bos;
}
}
public static class CharSequenceJavaFileObject extends SimpleJavaFileObject {
private CharSequence content;
public CharSequenceJavaFileObject(String className, CharSequence content) {
super(URI.create("string:///" + className.replace('.', '/') + JavaFileObject.Kind.SOURCE.extension),
JavaFileObject.Kind.SOURCE);
this.content = content;
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return content;
}
}
public static class ClassFileManager extends ForwardingJavaFileManager {
private JavaClassObject jclassObject;
public ClassFileManager(StandardJavaFileManager standardManager) {
super(standardManager);
}
@Override
public ClassLoader getClassLoader(Location location) {
return new SecureClassLoader() {
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
byte[] b = jclassObject.getBytes();
return super.defineClass(name, jclassObject.getBytes(), 0,
b.length);
}
};
}
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className,
JavaFileObject.Kind kind, FileObject sibling) throws IOException {
jclassObject = new JavaClassObject(className, kind);
return jclassObject;
}
}
}
And finally, my pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Debug</groupId>
<artifactId>Debug</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<finalName>pipe</finalName>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<configuration>
<mainClass>Debug</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
When I run this example with the command mvn compile exec:java, I get an error:
[INFO] --- exec-maven-plugin:1.2.1:java (default-cli) @ Debug ---
UNSUCCESSFUL:
compiler.err.cant.resolve
ERROR
30
30
38
string:
string:
symbol: class SayHello
I think the problem is the need to specify the class path and the output directory, but I'm not sure if this is the best way to fix this. I tried to add a line:
optionList.addAll(Arrays.asList("-classpath", "target/classes", "-d", "target/classes"));
, . "/", , .
, !
. , Maven .
main:
import org.jfree.data.xy.XYDataItem;
public class Debug {
public static void main(String[] args) {
DynamicCompiler compiler = new DynamicCompiler();
SayHello hello = compiler.getHello();
hello.sayHello();
XYDataItem xyDataItem = new XYDataItem(10,10);
}
}
pom.xml http://maven.apache.org/xsd/maven-4.0.0.xsd" > 4.0.0
<groupId>Debug</groupId>
<artifactId>Debug</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>jfree</groupId>
<artifactId>jfreechart</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
<build>
<finalName>pipe</finalName>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<goals>
<goal>exec</goal>
</goals>
</execution>
</executions>
<configuration>
<executable>java</executable>
<arguments>
<argument>-cp</argument>
<argument>target/classes/</argument>
<argument>Debug</argument>
</arguments>
</configuration>
</plugin>
</plugins>
</build>
</project>
:
[INFO] --- exec-maven-plugin:1.2.1:exec (default-cli) @ Debug ---
Hello World
Exception in thread "main" java.lang.NoClassDefFoundError: org/jfree/data/xy/XYDataItem
at Debug.main(Debug.java:9)
Caused by: java.lang.ClassNotFoundException: org.jfree.data.xy.XYDataItem
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
... 1 more
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
, , , , , maven-shade, -.
!