java - 使用runtime.exec()调用java方法

标签 java reflection jvm runtime.exec

在我的java代码中,类A具有以下行:

Process localProcess = Runtime.getRuntime().exec(myString);

其中 myString 是用户提供的输入,并在运行时传递给 exec()

A 类中还有一个公共(public)方法 doSomething()

我可以在运行时使用 exec() 以某种方式调用 doSomething() (通过反射、jdwp 等)吗?

最佳答案

启动一个新的 JVM 只是为了调用一个方法?首先,那会非常慢。其次,这是完全没有必要的!

我猜反射就是你想要的。这是一些示例代码。

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {

    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
        Class<Main> c = Main.class; // First get the class
        try {
            Method method = c.getMethod("doSomething"); // get the method by its name
            method.invoke(new Main()); // call it on a new instance of Main
        } catch (NoSuchMethodException e) {
           System.out.println("Method is not found"); // print something when the method is not found
        }
    }

    public void doSomething() {
        System.out.println("I have done something!");
    }
}

关于java - 使用runtime.exec()调用java方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39178125/

相关文章:

java - 性能说明: code runs slower after warm up

java - spring找不到我的bean

java - 无法使用 Morphia 连接到 MongoDb

java - 如何使用反射设置原始数组字段?

java - 调用Comparator比较方法中的方法

java - 守护线程阻止 JVM 终止 - 可能的原因?

java - 什么是 com.sun.proxy.$Proxy

java - 如何使用此网格适配器构造函数

java - 使用应用服务器的主要好处是什么?

java - 如何获取参数化类型的类引用