在我的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/