java - 获取java文件的动态执行结果

标签 java eclipse-plugin dynamic-execution

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

相关文章:

java - 如何在 ResourceChangeListener(eclipse 插件)中添加标记?

eclipse - : uploading code to lambda 期间发生内部错误

java - 安装插件后动态执行不起作用

java - Vaadin:向 TextField 添加占位符

java - GWT 和泛型

c - Eclipse System-Workbench (Win 10 v4.6.3) 在包含 .h 文件时忽略大小写

.net - 有没有办法诱使 .NET JIT 编译器运行另一种方法?

c++ - 编译包含动态并行性的代码失败

java - 无法在 Java 中向经过身份验证的 Hyperledger Composer Rest 服务器发出发布请求

java - Java中通过web.xml加载项目时如何调用属性文件?