Java JavaCompiler.run()也编译匿名类

时间:2018-02-20 09:02:32

标签: java classloader dynamic-loading javacompiler

我正在尝试加载文本文件并编译它们。

File file = new File("Files/"+fileName+".java");
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, null, errStream, file.getAbsolutePath());

然后我将在以后加载编译的.class文件:

 public Class loadStrategyClass(File strategyClassFile) throws IOException
    {
        FileChannel roChannel = new RandomAccessFile(strategyClassFile, "r").getChannel();
        ByteBuffer buffer = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, (int)roChannel.size());

        return defineClass(strategyClassFile.getName(), buffer, (ProtectionDomain)null);
    }

我目前遇到两个问题: 第一个是我加载的.java文件是否包含匿名类。似乎JavaCompiler类不会编译它们。 线程“main”中的异常java.lang.IllegalAccessException:类Loader.ClassLoader无法使用修饰符“”

访问Files.myname.myclass $ 1类的成员

第二个: 有时我会得到NoClassDefFoundError的错误: 线程“main”中的异常java.lang.NoClassDefFoundError:Files / myname / myclass 尽管其他类将正确加载并且.class文件位于该路径中。

1 个答案:

答案 0 :(得分:0)

显然,您的loadStrategyClass是在自定义ClassLoader中定义的。问题是,对于您感兴趣的类只调用defineClass一次是不够的,您的类加载器必须能够按需解析类,通常是通过实现findClass,因此JVM可以解决依赖关系,比如内部类。

您没有指定如何获得strategyClassFile方法的loadStrategyClass参数。由于您在没有任何选项的情况下运行编译器,我想您只需查找相对于源文件的文件。要解析其他依赖项,需要知道类目录的实际根目录。定义存储类文件的位置时会变得容易得多,例如

// customize these, if you want, null triggers default behavior
DiagnosticListener<JavaFileObject> diagnosticListener = null;
Locale locale = null;

JavaCompiler c = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm
    = c.getStandardFileManager(diagnosticListener, locale, Charset.defaultCharset());

// define where to store compiled class files - use a temporary directory
Path binaryDirectory = Files.createTempDirectory("compile-test");
fm.setLocation(StandardLocation.CLASS_OUTPUT,
               Collections.singleton(binaryDirectory.toFile()));

JavaCompiler.CompilationTask task = c.getTask(null, fm,
    diagnosticListener, Collections.emptySet(), Collections.emptySet(),
    // to make this a stand-alone example, I use embedded source code
    Collections.singleton(new SimpleJavaFileObject(
        URI.create("string:///Class1.java"), Kind.SOURCE) {
            public CharSequence getCharContent(boolean ignoreEncodingErrors) {
                return "package test;\npublic class Class1 { public class Inner {} }";
            }
        }));
if(task.call()) try {
    URLClassLoader cl = new URLClassLoader(new URL[]{ binaryDirectory.toUri().toURL() });
    Class<?> loadedClass = cl.loadClass("test.Class1");
    System.out.println("loaded "+loadedClass);
    System.out.println("inner classes: "+Arrays.toString(loadedClass.getClasses()));
} catch(ClassNotFoundException ex) {
    ex.printStackTrace();
}

在上面的例子中,我们知道类目录的根,因为我们已经定义了它。这允许简单地使用现有的URLClassLoader而不是实现新类型的类加载器。当然,使用自定义文件管理器,我们也可以使用内存存储而不是临时目录。

您可以使用此API来发现生成的内容,这使您可以在不事先知道的情况下使用生成的类,您要编译的源文件中存在哪个包或内部类声明。

public static Class<?> compile(
    DiagnosticListener<JavaFileObject> diagnosticListener,
    Locale locale, String sourceFile) throws IOException, ClassNotFoundException {

    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm
        = c.getStandardFileManager(diagnosticListener, locale, Charset.defaultCharset());

    // define where to store compiled class files - use a temporary directory
    Path binaryDirectory = Files.createTempDirectory("compile-test");
    fm.setLocation(StandardLocation.CLASS_OUTPUT,
                   Collections.singleton(binaryDirectory.toFile()));

    JavaCompiler.CompilationTask task = c.getTask(null, fm,
        diagnosticListener, Collections.emptySet(), Collections.emptySet(),
        fm.getJavaFileObjects(new File(sourceFile)));
    if(task.call()) {
        Class<?> clazz = null;
        URLClassLoader cl = new URLClassLoader(new URL[]{binaryDirectory.toUri().toURL()});
        for(JavaFileObject o: fm.list(
            StandardLocation.CLASS_OUTPUT, "", Collections.singleton(Kind.CLASS), true)) {

            String s = binaryDirectory.toUri().relativize(o.toUri()).toString();
            s = s.substring(0, s.length()-6).replace('/', '.');
            clazz = cl.loadClass(s);
            while(clazz.getDeclaringClass() != null) clazz = clazz.getDeclaringClass();
            if(Modifier.isPublic(clazz.getModifiers())) break;
        }
        if(clazz != null) return clazz;
        throw new ClassNotFoundException(null,
            new NoSuchElementException("no top level class generated"));
    }
    throw new ClassNotFoundException(null,
        new NoSuchElementException("compilation failed"));
}

如果您使用它来动态绑定插件或模块,您可以扩展搜索以查找实现特定接口或具有特定注释的结果类。

相关问题