0

启动这样的(或等效的)Java 程序时:

Runtime.getRuntime().exec("java -jar someJar.jar")

是否可以获得对已启动程序的 JFrame 的引用,以便可以使用FEST之类的库(例如在测试中)实现自动化?

当程序在同一个虚拟机中启动时,很容易做到这一点,如下面的例子所示,但由于几个原因,我不能这样做。该程序必须与启动它的虚拟机/进程分开,如上所述或类似。但是,当使用上面的代码启动进程时,下面的 FEST 代码没有找到框架。

使用 FEST 和来自Java Reflection 的改编代码的示例。运行一个外部 jar 并引用它的类?:(FrameFixture只是 a 的自动化包装器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();
4

1 回答 1

1

不,您不能在另一个进程中获得对 JFrame 的引用。当您使用Runtime.exec()一个全新的操作系统进程时,它会创建自己的内存空间和保护。

要完成您想要的,您可以创建一个类似 JMX 的接口,该接口接受将在流程内执行操作或从流程报告回信息的命令。

于 2014-01-20T22:02:20.463 回答