MaryLee
MaryLee

Reputation: 23

Multiple classes in one java application each with a main function

I have multiple classes in one java application, each one of them has a main function. I currently have to start each class manually. Is there any possible way to run them together in a specific order. So, when one class finishes the second one starts automatically. I thought of making one executable file but do not know from where to start and how to do this with multiple main functions.

Upvotes: 0

Views: 135

Answers (5)

A4L
A4L

Reputation: 17595

How about writing a simple script (*.bat or *.sh) which runs your classes one after another:

java -cp myJar.jar  com.foo.mainClass1
java -cp myJar.jar  com.bar.mainClass2
java -cp myJar.jar  com.baz.mainClass3
// and so on

Upvotes: 1

Ingo
Ingo

Reputation: 36339

Say you want to run the main fnctions from A, B and C. So write another class (say D) with

public static void main(String args[]) {
    A.main(args);
    B.main(args);
    C.main(args);
}

Then run the D class.

Upvotes: 2

dooxe
dooxe

Reputation: 1490

One solution could be this one :

interface App
{
     public void execMain(String args[]);
}

class MyApp1 implements App
{
  public void execMain(String args[])
  {
     // Stuff for  App1
  }
}

class MyApp2 implements App
{
  public void execMain(String args[])
  {
     // Stuff for  App2
  }
}

//...

And your Main finally :

public class Main
{
  // The list of apps
  private static App apps[] = new App[]
  {
     new MyApp1(),
     new MyApp2(),
     // ...
  }

  public static void main(String args[])
  {
    for(App a : apps)
    {
      a.execMain(args);
    }
  }
}

This way you can add easily add other apps to be executed.

Upvotes: 0

Sahil Mehta
Sahil Mehta

Reputation: 1

You can simply call the main function of other class from one class. You can decide your sequence like Class A calls Class B's Main .

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533500

The main methods are just methods called main. If you want to call them in an order I would create a main method which calls each one in the order desired.

class ClassA {
    public static void main(String... args) {
        ClassB.main(args);
        ClassC.main(args);
        ClassD.main(args);
    }
}

Upvotes: 0

Related Questions