Java:Runtime.getRuntime()。exec() - 如何获取对已启动程序JFrame的引用?

时间:2014-01-20 21:55:14

标签: java swing user-interface junit fest

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

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

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

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

使用来自Java Reflection. Running a external jar and referring to its classes?的改编代码的FEST示例:(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();

1 个答案:

答案 0 :(得分:1)

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

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