mercredi 22 février 2017

Compile Java Code in a string

I write a simple java code in a String and want to execute dynamically when the program runs, below is my code:

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

public class CompliedClass {
    public static void main(String[] args) {
        String source = ""
                +"class Solution{"
                +"public int add(){"
                +"return 1+1;"
                +"}"
                +"}";

        //File root = new File("");
        File sourceFile = new File("./src/Solution.java");
        try {
            Files.write(sourceFile.toPath(), source.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(sourceFile.getPath());
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        if (compiler == null) {
            System.out.println("JDK required (running inside of JRE)");
        }else{
            System.out.println("you got it!");
        }

        int compilationResult = compiler.run(null, null, null,sourceFile.getPath());
        if(compilationResult == 0){
            System.out.println("Compilation is successful");
        }else{
            System.out.println("Compilation Failed");
        }

        try{
            URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { sourceFile.toURI().toURL() });
            Class<?> cls = Class.forName("Solution" , true, classLoader);
            Object instance = cls.newInstance();
            Method method = cls.getDeclaredMethod("add", null);
            System.out.println(method.invoke(instance, null));
        }catch(Exception e){
            System.out.println("something wrong");
        }

    }
}

The Problem with the code above is when I execute first time, I can not get the result, it seems the below code has an exception:

Object instance = cls.newInstance();

Then I execute the second time, it functions good, so the conclusion is when I run for the first time, the Solution class can not be found, which cause the exception below

java.lang.ClassNotFoundException: Solution

could someone help me fix this issue please?





Aucun commentaire:

Enregistrer un commentaire