when invoking a java method by method.invoke() its not returning any value instead print in the console log

77 views Asked by At

Hello please help me to find a solution for this problem, I'm creating an web compiler for java programs I have implemented the java inbuilt compiler class to compile the code and its also giving the output but it's giving output in the console and I want that output in the return object or some string variable so I can display the output in front. I'm attaching full code.

package online_compiler.web;
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;


public class compiler {
    public static void myMethod(String name) throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
    {
        int result;
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        String program = "public class Main{" + " public static void main (String [] args){"
            + " System.out.println (\"Hello, World\");"
            + " }" + "}";
        
        JavaSourceFromString jsfs = new JavaSourceFromString("Main", program);
        Iterable<? extends JavaFileObject> fileObjects = Arrays.asList( jsfs);
        java.util.List<String> options = new ArrayList<String>();
        options.add("-d");
        options.add("C:\\Program Files\\Java\\jdk-12.0.2\\bin");
        options.add( "-classpath");
        URLClassLoader urlClassLoader =
                (URLClassLoader)Thread.currentThread().getContextClassLoader();
       StringBuilder sb = new StringBuilder();
       for (URL url : urlClassLoader.getURLs()) {
           sb.append(url.getFile()).append(java.io.File.pathSeparator);
       }
       sb.append("C:\\\\Program Files\\\\Java\\\\jdk-12.0.2\\\\bin");
       options.add(sb.toString());

       StringWriter output = new StringWriter();
       boolean success = compiler.getTask( output, null, null, options, null, fileObjects).call(); 
       if(success) {
           name = output.toString();
           System.out.print(output);
           java.io.File root = new java.io.File("C:\\\\Program Files\\\\Java\\\\jdk-12.0.2\\\\bin");
           URLClassLoader classLoader;
        try {   
            classLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() });
                Object obj = null;
               Class<?> cls = Class.forName("Main", true, classLoader);
               try {
                obj = cls.newInstance();
            } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
                Method m = cls.getMethod("main", new Class[] { String[].class });
                Object[] _args = new Object[] { new String[0] };
                Object retobj =  m.invoke(obj, _args);
                System.out.println(retobj);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

           //logger.info( LOG_PREFIX + "Class has been successfully compiled");
       } else {
           //throw new Exception( "Compilation failed :" + output);
       }
        
    }
    
    static Iterable<JavaSourceFromString> getJavaSourceFromString(String code) {
        final JavaSourceFromString jsfs;
        jsfs = new JavaSourceFromString("code", code);
        return new Iterable<JavaSourceFromString>() {
          public Iterator<JavaSourceFromString> iterator() {
            return new Iterator<JavaSourceFromString>() {
              boolean isNext = true;

              public boolean hasNext() {
                return isNext;
              }

              public JavaSourceFromString next() {
                if (!isNext)
                  throw new NoSuchElementException();
                isNext = false;
                return jsfs;
              }

              public void remove() {
                throw new UnsupportedOperationException();
              }
            };
          }
        };
      }
}
class JavaSourceFromString extends SimpleJavaFileObject {
      final String code;

      JavaSourceFromString(String name, String code) {
        super(URI.create("string:///" + name.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE);
        this.code = code;
      }
      
      public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return code;
          }
}


The main driver code is this enter image description here

output in the console log

I have tried many things searching on internet but nothing worked. I want that output in an object or a string variable so I can use that output or that string to front end.

1

There are 1 answers

2
siggemannen On

The method you call is static void main. It doesn't return any value. If you create a method that actually returns something, it should work better