2

我有一个程序将字符串写入 .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(); 
    }
}
4

1 回答 1

2

您的字节数组不是有效的字节码。如果是,它将以魔术字符串 (hex) 开头0xCAFEBABE。相反,您的第一个字节是1885430635(十进制),即 hex 0x7061636b,一次读取一个字节会给出 ASCII characters pack,这只是包声明的开始。

换句话说,您正试图像加载字节码一样加载文本文件,显然 Java 无法从这样的字节流构造任何类。

于 2012-12-05T09:20:19.750 回答