Possible Duplicate:
Execute another jar in a java program
Basically I want to run an external .jar from the one I’m working on now.
I.e. I want to run foo.jar from bar.jar
I’ve tried using Runtime and Process to execute “java -jar foo.jar”, but it opens foo.jar and then it closes immediately. Any tips?
The easiest solution (as Thorn pointed out) would be to have the jar as a build-time dependency and invoke it statically from your code:
But if that is not possible, you can use a
URLClassLoaderto load the jar dynamically. If the jar is indeed runnable, then you can read the main class fromMETA-INF/MANIFEST.MFand invokemainvia reflection.This is a different approach from creating a separate process, as the external code will run in the same process as your application. Perhaps this is desirable, perhaps not – that depends on the situation.
Below’s a (hastily written and flawed) sample helper class that does just that.
Sample usage: