我有一个程序将字符串写入 .java 文件,用于javax.tools
将该 .java 文件编译为 .class 文件,然后我使用修改后的 ClassLoader 尝试获取Runnable
该类的实例(通过将其转换为字节数组并ClassLoader.defineClass
用于获取实例)。但是……我有问题。当程序试图获取该类的实例时,它注意到它没有以正确的方式编译。我得到一个ClassFormatError
写着Incompatible magic value 1885430635 in class file <Unknown>
. 这是我的(目前相当草率)代码:
import java.io.*;
import java.security.SecureClassLoader;
public class EnhancedClassLoader extends SecureClassLoader
{
public Object createObjectFromFile(String fileName) throws
InstantiationException, IOException, IllegalAccessException
{
File file = new File(fileName);
definePackage("compClassPack", null, null, null, null, null, null, file.toURI().toURL());
byte[] classBytes = null;
//ReadFileToByteArray
{
FileInputStream fis = new FileInputStream(file);
int size = (int)file.length();
classBytes = new byte[size];
int offset = 0;
int readed;
while (offset < size && (readed = fis.read(classBytes, offset, size - offset)) != -1)
{
offset += readed;
}
fis.close();
}
Class<?> clazz = defineClass(null, classBytes, 0, classBytes.length);
//The error is thrown here! ^^^
return clazz.newInstance();
}
}
.
import java.io.*;
import javax.tools.*;
public class Main
{
public static void main(String[] args)throws Exception
{
File file = new File("Sample.java");
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
String code =
"package compClassPack;\n" +
"public class Sample implements Runnable\n" +
"{\n" +
" public Sample(){}\n\n" +
" public static void main(String[] args)\n" +
" {\n" +
" new Sample().run();\n" +
" }\n\n" +
" public void run()\n" +
" {\n" +
" System.out.println(\"It worked! :D\");\n" +
" }\n" +
"}";
for(byte ch : code.getBytes())
{
if((char)ch!='\n')
bw.write((char)ch);
else
bw.newLine();
}
bw.flush();
bw.close();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(file);
JavaCompiler.CompilationTask ct = compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits);
ct.call();
for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics())
System.out.format("Error on line %d in %d%n",
diagnostic.getLineNumber(),
((FileObject)diagnostic.getSource()).toUri());
fileManager.close();
EnhancedClassLoader loader = new EnhancedClassLoader();
Runnable runs = (Runnable) loader.createObjectFromFile(file.getAbsolutePath());
runs.run();
}
}