Launch a java application from another java applic

2019-05-01 01:03发布

I'm doing a Java Record/Replay tool and I need to launch Java applications from my main Java app. I need access to the EventDispatchThread in order to intercept the events and record them, so I'm launching the application through reflection with (code snippet simplified):

Class<?> app = Class.forName(mainClass);
Method m = app.getMethod("main", new Class[] { String[].class }); 
m.invoke(null, new Object[] { new String[] {} });

I previously dynamically load all the jars to the classpath and the application is launching almost perfectly.

The problem occurs when the application needs to access any file and does it with relative paths. Because the application is launched through my application the path is not the same as launched from its normal path and the files are not found.

What can I do to solve this problem? dynamically change the execution environment? any ideas?

2条回答
疯言疯语
2楼-- · 2019-05-01 01:15

I would suggest loading your code as a "Java Agent" whilst starting the target application.

(With your method you will also find that the system class loader is wrong.)

查看更多
放荡不羁爱自由
3楼-- · 2019-05-01 01:23

In general, there's no way to do this.

http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=30b24551130ee4ffffffffc17df8d7ce8a9c3?bug_id=4117557

You can try System.setProperty("user.dir", "C:\\Some\\Location"); but it probably won't work for all cases and will give you weird behavior.

It's a pretty bad design for an app to rely on the directory from which it was launched.

The best advice I can give you is to launch your app from the directory from which the misbehaving app expects to be launched (assuming you know what that directory is).

Otherwise, hell, copy/symlink the data files into your directory so that the client app can find them...

查看更多
登录 后发表回答