Reputation: 8790
I am super new to Java. I have a Java program which is deployed to a server as a .jar file. I have another executable program, also in Java, that I need it to call (in myjar.jar). At first I was basically shelling out and creating another java instance like:
List<String> commandAndParameters = new ArrayList<String>(Arrays.asList("java", "-jar", "myjar.jar"
ProcessBuilder builder = new ProcessBuilder();
builder.command(commandAndParameters);
Process process = builder.start();
...
This hasn't been working too well and it's also slow to launch a second instance of Java, so I thought I would just import the jar into my program and run the class directly. The main class is called Main and of course the method of the class that I would be calling is main. Which is a little weird, but I figured it could work (there's no rule saying you can't have another object with a main method, right?)
I'm not really sure how to import it though. I extracted myjar.jar to look at the structure and the class I want to use is at a/b/c/Main.class
. The jar exists in the root directory of the program from which I'm trying to call it, so I naively tried import a.b.c.Main
but of course that didn't work. I'm using IntelliJ and tried adding the .jar as a module (Project Structure->Modules->+->Import Module), I guess to add it to my classpath, but it just says "Cannot import anything from myjar.jar"
I'm using Maven for what it's worth. I need to get both IntelliJ working, and the jar produced by Maven working for when I build.
So clearly, I am super lost. I'm not even sure if the way I'm trying to do this is ideal - it definitely seems dirty to be importing another Jar just so I can run a second main method in code. So I'd appreciate any pointers on the "right way" to do things as well as how to get these things working.
Upvotes: 0
Views: 1116
Reputation: 839
If you're building your project via Maven, you need to add your import .jar file as a dependency to the project you're importing the .jar from
If your other project (the .jar you want to import) is already being built by Maven, that's super easy to do. If not, you can install it to your local .m2 repo with mvn install:install-file (see https://maven.apache.org/guides/mini/guide-3rd-party-jars-local.html)
After you have the .jar referenced in your pom file IntelliJ will recognize it.
It is also possible to manually add a .jar file as a dependency to your module in IntelliJ. I'd recommend avoiding that if possible if you're already using Maven. If you need to, you can go to your project settings, then "Modules", pick your module, and select "Dependencies", then click the plus sign to add a .jar dependency to your module.
Upvotes: 1