Java将编程编译的类添加到当前Class的可用引用列表中

时间:2012-05-07 11:29:51

标签: java

作为Java ClassNotFoundException when reading object from a stream

的扩展

我已经添加了服务器接收.java文件的能力,它可以编译它。但是,我仍然得到相同的ClassNotFoundException。如何让服务器查看并使用它编译的类来从objectInputStream中读取对象?

在serverSide上读取和编译.java的代码:

    private void doNewWorkUnitDefinition(Object object) {
    NewWorkUnitDefinition newWorkUnitDefinition = (NewWorkUnitDefinition)object;
    byte[] bytes = newWorkUnitDefinition.getBytes();
    String name = newWorkUnitDefinition.getName();

    if (isClient) 
        client.gotNewWorkUnitDefinition(bytes, name);
    else {
        String executionPath = System.getProperty("user.dir");
        File file = new File(executionPath, name);
        try {
            FileOutputStream fileOut = new FileOutputStream(file);
            fileOut.write(bytes);
            fileOut.close();
            System.out.println("Just wrote a file to: " + file.getAbsolutePath());

            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            compiler.run(System.in, System.out, System.err, file.getAbsolutePath());

            ClassLoader cl_old = Thread.currentThread().getContextClassLoader();
            ClassLoader cl_new = new URLClassLoader(new URL[] { file
                    .getParentFile().toURI().toURL() }, cl_old);
            System.out.println("WorkUnitFile: " + file.getAbsolutePath());
            Class compiledClass = cl_new.loadClass(file.getName()
                    .replace(".java", ""));
            this.

            sendConfirmDefinitionReceipt();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2 个答案:

答案 0 :(得分:0)

我过去所做的是通过调用当前类加载器的defineClass方法来加载类(使用反射)

http://sourceforge.net/projects/essence/files/Essence%20Java%20Config.%20Files/Essence%20JCF%201.02/

答案 1 :(得分:0)