启动这样的 Java 程序(或等效程序)时:
Runtime.getRuntime().exec("java -jar someJar.jar")
是否可以获取对已启动程序的 JFrame 的引用,以便可以使用 FEST 等库实现自动化(例如在测试中)?
当程序在同一虚拟机内启动时,很容易做到这一点,如下例所示,但由于多种原因我无法做到这一点。程序必须与启动它的虚拟机/进程分开,如上面或类似的。然而,当使用上面的代码启动进程时,下面的FEST代码没有找到框架。
使用 FEST 和来自 Java Reflection. Running a external jar and referring to its classes? 的改编代码的示例: (FrameFixture
只是 JFrame
的自动化包装器):
Thread t = new Thread(new Runnable() {
public void run() {
File file = new File("someJar.jar");
URLClassLoader cl;
try {
cl = new URLClassLoader( new URL[]{file.toURI().toURL()} );
}
catch (MalformedURLException e) {}
Class<?> clazz = null;
try {
clazz = cl.loadClass("Main");
}
catch (ClassNotFoundException e) {}
Method main = null;
try {
main = clazz.getMethod("main", String[].class);
}
catch (NoSuchMethodException e) {}
try {
main.invoke(null, new Object[]{new String[]{}});
}
catch (Exception e) {}
}
});
t.start();
GenericTypeMatcher<JFrame> matcher = new GenericTypeMatcher<JFrame>(JFrame.class) {
protected boolean isMatching(JFrame frame) {
return "TestFrame".equals(frame.getTitle()) && frame.isShowing();
}
};
FrameFixture frame = WindowFinder.findFrame(matcher).using(BasicRobot.robotWithCurrentAwtHierarchy());
frame.maximize();
最佳答案
不,您无法在另一个进程中获取对 JFrame 的引用。当您使用 Runtime.exec() 时,会创建一个全新的操作系统进程,并具有自己的内存空间和保护。
要完成您想要的任务,您可以创建一个类似 JMX 的界面,该界面接受将在流程中执行操作或从流程中报告信息的命令。
关于Java:Runtime.getRuntime().exec() - 如何获取对已启动程序 JFrame 的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21244953/