Saturday, February 23, 2019

swing - Java: Runtime.getRuntime().exec() - how to get reference to launched programs JFrame?



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 matcher = new GenericTypeMatcher(JFrame.class) {
protected boolean isMatching(JFrame frame) {
return "TestFrame".equals(frame.getTitle()) && frame.isShowing();
}
};

FrameFixture frame = WindowFinder.findFrame(matcher).using(BasicRobot.robotWithCurrentAwtHierarchy());

frame.maximize();

Answer



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.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...