All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.lq.doc.load.JavaFileLoader Maven / Gradle / Ivy

package com.lq.doc.load;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;

public class JavaFileLoader {

    public static  Class loadClass(String fileName,StringBuilder javaFileContent) throws ClassNotFoundException {
        String loadingContent = javaFileContent.delete(0, javaFileContent.indexOf(";") + 1).toString();
        Map compile = compile(fileName, loadingContent);
        MemoryClassLoader memoryClassLoader = new MemoryClassLoader(compile);
        String className = fileName.substring(0, fileName.length() - 5);
        return memoryClassLoader.loadClass(className);
    }

    private static Map compile(String javaName, String javaSrc) {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager stdManager = compiler.getStandardFileManager(null, null, null);
        try (MemoryJavaFileManager manager = new MemoryJavaFileManager(stdManager)) {
            JavaFileObject javaFileObject = MemoryJavaFileManager.makeStringSource(javaName, javaSrc);
            JavaCompiler.CompilationTask task = compiler.getTask(null, manager, null, null, null, Collections.singletonList(javaFileObject));
            if (task.call()) return manager.getClassBytes();
            else return null;
        } catch (IOException e) {
            return null;
        }

    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy