我正在使用下面的方法来执行一个名为 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
注意 类型转换为 (String) thisMethod.invoke(instance,(Object)m);没有用..它给出了空值。
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)
{
}
}
最佳答案
invoke
方法的返回值是一个对象。所以这意味着它可能返回一个字符串,但也可能返回任意数量的其他值,甚至是 null。
因此,只要确保在获得结果时正确处理即可。
Object result = thisMethod.invoke(instance,(Object)m);
if (result != null && (result instanceof String)){
// my string result
}
还要确保在您调用的方法中,您不仅打印了一些东西,而且还返回了您想要的值。
关于java - 获取java文件的动态执行结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16990972/