Resolve jar dependencies automatically-Collection of common programming errors
The best way is to use maven. If dependencies are defined in maven you can just run mvn dependency:tree
to retrieve needed information. Please refer to this article for details.
If you do not use maven you probably have to use tools like jdepend. But be careful: such tools cannot really retrieve all dependencies. It is impossible to retrieve dependency on dynamically loaded class or API being called by reflection using static analysis only. Full solution may be achieved only if you are running your application, test it with all possible scenarios and check what classes are loaded by class loader. If you have 100% test coverage you can run your application using option -verbose:class
and then run all unit tests against your application. You will get a list of all loaded classes. Now put this list to file and write shell script that analyses the classes list and transforms it to jars list.