我有一个包含两个类的java源文件:
package com.example;
public class Test {
public void sayHello() {
String hello = new HelloProducer().getHello();
System.out.println(hello);
}
public static void main(String[] args) {
new Test().sayHello();
}
}
class HelloProducer {
public String getHello() {
return "hello";
}
}
我想使用 Java SDK 以编程方式编译这个 java 源文件,这是我尝试过的。
package com.example;
import java.io.IOException;
import javax.tools.*;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
public class Compiler {
public static void main(String[] args) throws IOException {
byte[] classBytes = compile();
// how to write classBytes to two class files: HelloProducer.class and Test.class?
}
public static byte[] compile() throws IOException {
String javaSource = "package com.example;\n" +
"\n" +
"public class Test {\n" +
" public void sayHello() {\n" +
" String hello = new HelloProducer().getHello();\n" +
" System.out.println(hello);\n" +
" }\n" +
" public static void main(String[] args) {\n" +
" new Test().sayHello();\n" +
" }\n" +
"}\n" +
"class HelloProducer {\n" +
" public String getHello() {\n" +
" return \"hello\";\n" +
" }\n" +
有效。我成功编译了这个java源代码并得到了一个字节数组classBytes。但问题来了:当你编译Test.javausing 时javac,你会得到两个类文件:Test.classand HelloProducer.class,但是现在我只有一个字节数组classBytes,我怎么能像 一样正确地将字节数组写入两个文件(Test.class和HelloProducer.class)javac?
相关分类