Reputation: 43
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)
{
}
}
Upvotes: 1
Views: 63
Reputation: 7507
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.
Upvotes: 3