1

我正在使用下面的方法来执行一个名为 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)
            {
            }

        }
4

1 回答 1

3

invoke方法的返回值是一个对象。所以这意味着它可以返回一个字符串,也可以返回任意数量的其他值,甚至是 null。

因此,请确保在获得结果时正确处理它。

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

还要确保在您调用的方法中,您不仅要打印一些东西,还要返回您想要的值。

于 2013-06-07T18:56:15.913 回答