动态编译java代码,该代码依赖于特定类加载器加载的类

时间:2016-12-05 21:11:21

标签: java groovy compilation jvm classloader

我们有能力动态编译java代码。 我至少知道Java-Runtime-CompilerInMemoryJavaCompiler

但似乎他们无法编译依赖于某个类加载器中某些类的类。

是否可以动态编译依赖于仅在特定类加载器中可用的类的java代码?让我们说:

ClassLoader classloader = ... // only this CL can load class 'com.External'
String source = "public class MyClass extends com.External {}";
Class<?> compiled = DesiredDynamicCompiler.compile("MyClass", source, classloader); 
// last argument is like an information to compiler where to search all dependencies

提供更多见解:我想在java中完成GroovyClassLoader在groovy中可以做什么:

GroovyClassLoader groovyClassLoader = new GroovyClassLoader(classLoader);
Class<?> parsedClass = groovyClassLoader.parseClass("some source");

该代码可以解析依赖于仅在指定的类加载器中可用的类的类。

2 个答案:

答案 0 :(得分:1)

您应该拥有类路径上的所有依赖项。您引用的工具无论如何都使用封面下的Java Compiler API。

它不与当前JVM内存中的类进行交互,它只搜索类路径中的依赖项。

您可以关注CompilerUtils - &gt; com.sun.tools.javac.api.JavacTool - &gt;进一步了解那里发生了什么。

您可以尝试做的一件事是将动态编译的依赖项作为.class文件转储到类路径中的适当位置,以便您的编译过程能够将它们提取出来。

答案 1 :(得分:1)

除非能够提供其定义类的类字节,否则无法使用ClassLoader作为参考。即,如果您有一个代表顶级类的Class实例,则可以使用classInstance.getResourceAsStream(classInstance.getSimpleName()+".class")来尝试获取类字节。如果您可以访问构成动态类的字节,则可以通过JavaFileManager实现将它们提供给java编译器。

编译器API是标准API的一部分,不需要第三方库。下面的代码通过首先编译测试类,然后根据刚刚在上一步中创建的类设置编译第二个类的必要环境来演示这一点:

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

// the first class, to be present at runtime only
String class1 = "package test;\npublic class Class1 {}";
JavaCompiler c = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm
    = c.getStandardFileManager(diagnosticListener, locale, Charset.defaultCharset());
// define where to store compiled class files - use a temporary directory
fm.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(
        Files.createTempDirectory("compile-test").toFile()));
JavaCompiler.CompilationTask task = c.getTask(null, fm,
    diagnosticListener, Collections.emptySet(), Collections.emptySet(),
    Collections.singleton(new SimpleJavaFileObject(
        URI.create("string:///Class1.java"), Kind.SOURCE) {
            public CharSequence getCharContent(boolean ignoreEncodingErrors) {
                return class1;
            }
        }));
if(task.call()) {
    FileObject fo = fm.getJavaFileForInput(
            StandardLocation.CLASS_OUTPUT, "test.Class1", Kind.CLASS);
    // these are the class bytes of the first class
    byte[] class1bytes = Files.readAllBytes(Paths.get(fo.toUri()));

    // the actual task: define a class dependent on the first class
    String class2 = "package test;\npublic class Class2 { Class1 variable; }";

    // create a file object representing the dynamic class
    JavaFileObject jo = new SimpleJavaFileObject(
        URI.create("runtime:///test/Class1.class"), Kind.CLASS) {
            @Override public InputStream openInputStream() throws IOException {
                return new ByteArrayInputStream(class1bytes);
            }
        };

    // and a custom file manager knowing how to locate that class
    JavaFileManager myFM = new ForwardingJavaFileManager(fm) {
        @Override
        public JavaFileObject getJavaFileForInput(
                JavaFileManager.Location location, String className, Kind kind)
                throws IOException {
            if(location==StandardLocation.CLASS_PATH&&className.equals("test.Class1")) {
                return jo;
            }
            return super.getJavaFileForInput(location, className, kind);
        }

        @Override
        public boolean hasLocation(JavaFileManager.Location location) {
            return location==StandardLocation.CLASS_PATH || super.hasLocation(location);
        }

        @Override
        public Iterable list(JavaFileManager.Location location,
                String packageName, Set kinds, boolean recurse) throws IOException {
            if(location==StandardLocation.CLASS_PATH
                    && (packageName.equals("test") || recurse&&packageName.isEmpty())) {
                return Collections.singleton(jo);
            }
            return super.list(location, packageName, kinds, recurse);
        }

        @Override
        public String inferBinaryName(
                JavaFileManager.Location location, JavaFileObject file) {
            if(file==jo) return "test.Class1";
            return super.inferBinaryName(location, file);
        }
    };
    // compile the second class using the custom file manager to locate dependencies
    task = c.getTask(null, myFM,
        diagnosticListener, Collections.emptySet(), Collections.emptySet(),
        Collections.singleton(new SimpleJavaFileObject(
            URI.create("string:///Class2.java"), Kind.SOURCE) {
                public CharSequence getCharContent(boolean ignoreEncodingErrors) {
                    return class2;
                }
            }));
    if(task.call()) {
        fo = fm.getJavaFileForInput(
            StandardLocation.CLASS_OUTPUT, "test.Class2", Kind.CLASS);
        // there we have the compiled second class
        byte[] class2bytes = Files.readAllBytes(Paths.get(fo.toUri()));
    }
}

当然,这只是为了证明这一原则。您肯定希望为文件对象创建工厂方法,并使用Map来记住它们等。

也可以使用自定义内存存储替换临时目录。但关键的一点是,编译器需要能够访问类字节。它不会使用加载的运行时类。