Dakshila Kamalsooriya Dakshila Kamalsooriya - 1 year ago 63
Java Question

Java: Call a main method from a main method in another class

I have a set of Java files in the same package, each having main methods. I now want the main methods of each of the classes to be invoked from another class step by step. One such class file is Splitter.java. Here is its code.

public static void main(String[] args) throws IOException {

InputStream modelIn = new FileInputStream("C:\\Program Files\\Java\\jre7\\bin\\en-sent.bin");
FileInputStream fin = new FileInputStream("C:\\Users\\dell\\Desktop\\input.txt");
DataInputStream in = new DataInputStream(fin);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine = br.readLine();

try {
SentenceModel model = new SentenceModel(modelIn);
SentenceDetectorME sentenceDetector = new SentenceDetectorME(model);
String sentences[] = sentenceDetector.sentDetect(strLine);

for (int i = 0; i < sentences.length; i++) {
} catch (IOException e) {
} finally {
if (modelIn != null) {
try {
} catch (IOException e) {

I now want this to be invoked in
inside a main method.
So how can I do this? There are several other class files having main methods with
which have to be invoked in

Update -

I have main methods having
as well as main methods not having
that has to be invoked in

Answer Source

First of all, what you should probably do is refactor your code so each main method calls some other method, and then AllMethods makes calls to those new methods. I can imagine there might be some cases where it's useful if you're just trying to, for example, write some test code, but usually you wouldn't want to call main methods directly. It's just harder to read.

If you want to try it though, it's pretty easy, you just call the main method like any other static method. I once in college wrote a web server where, to handle authentication, I recursed on the main method. I think I got a C because it was unreadable code, but I had fun writing it.

class AllMethods {
    public void callsMain() {
        String[] args = new String[0];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download