簡體   English   中英

Java:從另一個類的主方法調用主方法

[英]Java: Call a main method from a main method in another class

我在同一軟件包中有一組Java文件,每個文件都有主要方法。 現在,我希望逐步從另一個類中調用每個類的主要方法。 這樣的類文件之一是Splitter.java。 這是它的代碼。

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();
    System.out.println(strLine);

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

        System.out.println(sentences.length);
        for (int i = 0; i < sentences.length; i++) {
            System.out.println(sentences[i]);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (modelIn != null) {
            try {
                modelIn.close();
            } catch (IOException e) {
            }
        }
        fin.close();
    }
}

我現在希望在主要方法的AllMethods.java調用AllMethods.java 那我該怎么做呢? 還有其他一些類文件,這些類文件具有帶有IOException主要方法,必須在AllMethods.java文件中進行調用。

更新-

我有具有IOException主要方法以及沒有IOEXception主要方法,必須在AllMethods.java調用AllMethods.java

你可以做到的。 主方法也和其他靜態方法一樣

public static void main(String[] args) throws IOException {
 ....// do all the stuff


Splitter.main(args); // or null if no args you need
}

首先,您可能應該做的就是重構代碼,以便每個主要方法調用其他方法,然后AllMethods調用這些新方法。 我可以想象,在某些情況下,如果您只是想嘗試編寫一些測試代碼,則很有用,但是通常您不想直接調用主方法。 很難閱讀。

如果您想嘗試一下,那很簡單,您只需像其他靜態方法一樣調用main方法即可。 我曾經在大學里寫過一個Web服務器,在其中處理身份驗證,我使用了main方法。 我認為我得到了C,因為它是不可讀的代碼,但是我寫它很有趣。

class AllMethods {
    public void callsMain() {
        String[] args = new String[0];
        Splitter.main(args);
    }
}

在Main.java中,main方法應添加throws Exception,如下所示:

package com.company;

import java.io.FileNotFoundException;

public class Main extends makeFile {

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

        makeFile callMakeFile = new makeFile();

        makeFile.main(args);
        // cannot figure out how to call the main method from the makeFile class here...
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM