w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Dynamic Compilation in Memory for Java for classes and classes that have dependencies on those classes

I believe your problem is in the JavaSourceFromString class, which needs to encode a URI for the class name:

@Test
public void test(){
    Map<String, String> code = new HashMap<String, String>();

    code.put("example.A",
            "package example;
" +
                    "public class A {
" +
                    "    public A() {
" +
                    "        doSomething();
" +
                    "    }
" +
                    "}");

    code.put("example.B",
            "package example;
" +
            "public class B {
" +
            "    private A holderForA;
" +
            "    public B() {
" +
            "        this.holderForA = new A();
" +
            "    }
" +
            "}");

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new
DiagnosticCollector<JavaFileObject>();
    List<JavaFileObject> compilationUnits = new
ArrayList<JavaFileObject>();
    for(String key : code.keySet()) {
        String toCompile = code.get(key);
        JavaFileObject file = new Source(key, JavaFileObject.Kind.SOURCE,
toCompile);
        compilationUnits.add(file);
    }
    JavaCompiler.CompilationTask task = compiler.getTask(null, null,
diagnostics, null, null, compilationUnits);
   
System.out.println(task.call()+diagnostics.getDiagnostics().toString());
//passes every time
}

public class Source extends SimpleJavaFileObject {
    private final String content;

    public Source(String name, Kind kind, String content) {
        super(URI.create("memo:///" + name.replace('.', '/') +
kind.extension), kind);
        this.content = content;
    }

    @Override
    public CharSequence getCharContent(boolean ignore) {
        return this.content;
    }
}




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.