我正在使用下面的方法来执行一个名为 NewFile.java 的文件。
行thisMethod.invoke(instance,(Object)m); 自动运行 NewFile.java 并在控制台中打印结果[如果存在],无论如何我可以在字符串中获得执行结果
NB 类型转换为 (String) thisMethod.invoke(instance,(Object)m); 没用..它给出了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)
{
}
}