mercredi 26 août 2015

How to write the main method result, called by Reflection, to a string.

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.io.*;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import marea.GetPackage;

public class Execution extends ClassLoader {

    @SuppressWarnings("resource")
    public void invokeClassMethod(File source, String classBinName, String methodName){


    try{

        System.setProperty("java.home", "C:\\Program Files\\Java\\jdk1.8.0_51\\jre");   

        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

        int compResult = compiler.run(null, null, null, source.getPath());

        if (compResult != 0) {
            System.out.println("compil!");
        }
        else{ 

                try {

                    File file = new File("C:\\Users\\abc\\");

                    URL url = file.toURI().toURL(); 

                    URL[] urls = new URL[] { url }; 

                    ClassLoader loader = new URLClassLoader(urls);

                    Class <?> thisClass = loader.loadClass(classBinName);

                    Constructor<?> constructor = thisClass.getConstructor();

                    Object Obj = constructor.newInstance();         

                    Method myMethod = thisClass.getDeclaredMethod("main",new Class[] { String[].class });

                    myMethod.setAccessible(true);

                    myMethod.invoke(Obj,new Object[] { new String [0] });

                }
                catch (Exception e){
                    e.printStackTrace();
                }
        }
    }
    catch (Exception e){
        e.printStackTrace();
    }

}

public static void main (String args[]){
    Execution javaClassLoader = new Execution();

    File source = new File("C:\\Users\\abc\\HelloWorld.java"); 

    String pak = GetPackage.getPackage(source);
    String clas = GetPackage.getClass(source);
    String classNameToBeLoaded;

    if (pak != "")  classNameToBeLoaded = pak + "." + clas;
    else    classNameToBeLoaded = clas;

    javaClassLoader.invokeClassMethod(source,classNameToBeLoaded,"main");
   }
}

If I run this I will get "Hello, World" message on the console. The message is the result of the main method of the HelloWorld.class file . Because the main method does not have a returned type and it is called by reflection, I do not know how to get the result and put it in a String variable.

Can you give me some ideas, please? (with code)





Aucun commentaire:

Enregistrer un commentaire