1

I am using the method below to execute a file called NewFile.java.

The line thisMethod.invoke(instance,(Object)m); automatically runs the NewFile.java and prints the result [if existed] in the console, Is there anyway that I can obtain the result of execution in a String

N.B. Typecasting as (String) thisMethod.invoke(instance,(Object)m); didn't work .. It gives null.

public static void runIt(String fileToCompile,String packageName) throws ClassNotFoundException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException, SecurityException, NoSuchMethodException
        {
            File file = new File(fileToCompile);

            try
            {
                URL url = file.toURL(); // file:/classes/demo
                URL[] urls = new URL[] { url };
                ClassLoader loader = new URLClassLoader(urls);
                Class<?> thisClass = classLoader.loadClass("NewFile");
                Object newClassAInstance = thisClass.newInstance();
                Class params[] = new Class[1];
                params[0]=String[].class;
                Object paramsObj[] = {};
                String m=null;
                Object instance = thisClass.newInstance();
                Method thisMethod = thisClass.getDeclaredMethod("main", params);
                r2+="method = " + thisMethod.toString();
                String methodParameter = "a quick brown fox";
               thisMethod.invoke(instance,(Object)m);

            }
            catch (MalformedURLException e)
            {
            }

        }
CSstudent
  • 43
  • 6

1 Answers1

3

The return value from the invoke method is an Object. So that means it could be returning a string, but also any number of other values, or even null.

So just make sure when you get the result that you handle it properly.

Object result = thisMethod.invoke(instance,(Object)m);
if (result != null && (result instanceof String)){
    // my string result
}

Also make sure that in the method you are invoking that you are not only printing something, but also returning the value you want.

greedybuddha
  • 7,488
  • 3
  • 36
  • 50
  • I am working on a plugin so this prints the result of execution in the original Eclipse's console and prints the result which is null in the plugin's console .. Any help ? – CSstudent Jun 07 '13 at 18:59
  • 1
    you need to change the method you are calling to return a String. If that method doesn't return a String, then you will need to make or call another method. – greedybuddha Jun 07 '13 at 19:02
  • Where is the string I'm gonna return ?? The problem is that I can't get the result in a variable – CSstudent Jun 07 '13 at 19:07
  • 1
    I'm talking about "inside" of the 'main' method you are invoking. If that is `public void` then you will never get a String and you will need to create your own method that returns a String, or modify `main` to be `public String main` – greedybuddha Jun 07 '13 at 19:09