在内存中,我构建了这个字符串:
package consume;
public class Consumer {
public void consume(String message){
System.out.println(new produce.Producer().produce(message));
}
}
在我的文件系统上,我C:\Users\hooch\Desktop\produce\Producer.class
从这个来源构建:
package produce;
public class Producer {
public String produce(String message){
return "THIS IS THE MESSAGE: " + message;
}
}
我使用org.eclipse.jdt.internal.compiler.tool.EclipseCompiler
并传递这些选项:
Arrays.asList(new String[] {"-cp", "C:\\Users\\hooch\\Desktop"});
我尝试编译它但得到这个错误
1. ERROR in \Consumer.java (at line 4)
System.out.println(new produce.Producer().produce(message));
^^^^^^^
produce cannot be resolved to a type
如果我在调用 EclipseCompiler 的项目中有类produce.Producer,它就可以工作。(我不需要在选项中指定类路径)现在的问题是:如何正确指定类路径,以便内存中的代码可以访问外部类?
如果我将 -verbose 添加到选项中,我会得到
[parsing \Consumer.java - #1/1]
[reading java/lang/Object.class]
[reading java/lang/String.class]
[analyzing \Consumer.java - #1/1]
[reading java/lang/System.class]
[reading java/io/PrintStream.class]
[reading java/io/FilterOutputStream.class]
[reading java/io/OutputStream.class]
[reading java/io/Flushable.class]
[reading java/io/Closeable.class]
[reading java/lang/AutoCloseable.class]
----------
1. ERROR in \Consumer.java (at line 4)
System.out.println(new produce.Producer().produce(message));
^^^^^^^
produce cannot be resolved to a type
----------
[completed \Consumer.java - #1/1]
[1 unit compiled]
1 problem (1 error)Exception in thread "main" java.lang.NullPointerException
at impl.SimpleTestCompiler.executeCode(SimpleTestCompiler.java:137)
at impl.SimpleTestCompiler.main(SimpleTestCompiler.java:155)
好的,现在我确定它一定与类路径选项有关,因为我将 EclipseCompiler 换成了 javax.tools.ToolProvider.getSystemJavaCompiler() 并且我得到了关于未解析包的相同错误。