Question

When launching a Java program like this (or equivalent):

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

Is it possible to get a reference to the JFrame of the launched program so it can be automated with libraries like FEST (e.g in tests)?

It's easy to do this when the program is launched inside the same VM, as illustrated in this example below, but for several reasons I cannot do that. The program must be separated from the VM/process launching it like above or similar. However, when using the above code to launch the process, the FEST code below does not find the frame.

Example using FEST with adapted code from Java Reflection. Running a external jar and referring to its classes?: (FrameFixture is just an automation wrapper for 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();
Was it helpful?

Solution

No, you cannot get a reference to a JFrame in another process. When you use Runtime.exec() a totally new OS process is created with its own memory space and protections.

To accomplish what you want you could create a JMX-like interface that accepts commands that will either execute actions within a process or report back information from the process.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top