1

I'd like to start a main(String args[]) method that is contained in a *.jar I have to use (don't ask, I'm already fed up).

//this is my own class
class MyInitClass {
    public static void main(String args[]) {
          SomeJar.MainApp("-port", 8080);
    }
}


//this is a keen developers class
class MainApp {
    public static void main(String args[]) {
         //makes use of the arguments, like starting a socket server
    }
}

What is the best way to call such a main method from my own class, preferably in a separate Thread?

membersound
  • 81,582
  • 193
  • 585
  • 1,120

5 Answers5

4
new Thread(new Runnable() {
    public void run() {
        MainApp.main(new String[] { "-port", "8080" });
    }
}).start();
MC Emperor
  • 22,334
  • 15
  • 80
  • 130
greenkode
  • 4,001
  • 1
  • 26
  • 29
2

Whether the class is in another jar file or not is irrelevant. As long as the jar containing the clas is in the classpath, you can use it. And main is a static method like all the other static methods, so, to call it, you use the name of the class followed by the name of the method. It takes a String array as argument, so you need to passs it a String array. So assuming MainApp is in the package com.foo.bar, you just need

import com.foo.bar.MainApp;

class MyInitClass {
    public static void main(String args[]) {
        MainApp.main(new String[] {"-port", "8080"});
    }
}

This won't call the main methd in another thread (not sure why you want that). If you want to do it, then create a thread and call MainApp.main() from the run() method o the thread or Runnable.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1

You could add the .jar to your classpath, then just load up the class and call the static Main() method. ie:

String[] args = new String[] {"-port", "8080"};
MainApp.main(args);
Stewart
  • 17,616
  • 8
  • 52
  • 80
1

Two ways of doing it:

  1. If you don't mind running it in process, then you can run it as SomeJava.MainApp.main({"-port", "8080"}) ... That is provided the MainApp class is looking for arguments in that fashion.

  2. If you know the command line parameters that get passed for running that jar, then you can execute it using Runtime.exec()

Hope that helps.

Harsha R
  • 707
  • 6
  • 12
0

You can try to start the jar app by using the Process class.

strPath = "java -jar <path>"
Process proc = Runtime.getRuntime().exec(strPath);

strPath will be path to your jar file so . You can surround this in a Thread class to make it run in a separate thread.

Aakash
  • 1,860
  • 19
  • 30