2017-09-26 148 views
-3

這是我用於IRC類的代碼。如何從另一個類中調用類的主函數

import org.jibble.pircbot.*; 

public class IRCBotMain { 

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

    IRCBot bot = new IRCBot(); 
    bot.setVerbose(true); 
    bot.connect("irc.freenode.net"); 
    bot.joinChannel("#pircbot"); 

}} 

但是,當我嘗試做

public class Main extends JavaPlugin { 
    @Override 
    public void onEnable() { 
     this.getLogger().log(Level.INFO, "Loading up!"); 
     IRCBotMain.main(null); 
    } 
} 

這另一個類,編譯器失敗,Unhandled exception type Exception


謝謝大家,我解決了這個問題,但輸出並運行後。我得到這個錯誤: https://pastebin.com/ZdDxYK2k 我跟着這(https://bukkit.org/threads/pircbot-how-to-install-import.132337/),但這發生。 順便說一句我正在使用pircbot而不是pircbotx。

+0

這將是更好的移動目前是主要以它自己的公共方法的代碼。然後從main和external類中調用此方法。 – Dave

+0

歡迎來到Stack Overflow! 請參考[遊覽](/遊覽),環顧四周,閱讀[幫助中心](/幫助),特別是[如何提出一個好問題?](/ help/how-to-問)和[我可以在這裏問什麼問題?](/幫助/話題)。 ** - **作爲Java的初學者,您可以先瀏覽官方教程:https://docs.oracle.com/javase/tutorial/ –

+0

由於main(...)引發異常,它的調用應該包含在一個'try-catch'塊中 – Prashant

回答

1

IRCBotMain.main()方法你嘗試調用聲明扔Exception所以無論你調用一個方法,你必須:

  • 捕獲異常

或者

  • 申報拋出的異常

例如:

@Override 
public void onEnable() { 
    try { 
     this.getLogger().log(Level.INFO, "Loading up!"); 
     IRCBotMain.main(null); 
    } catch (Exception ex) { 
     // respond to this exception by logging it or wrapping it in another exception and re-throwing etc 
    } 
} 

或者

@Override 
public void onEnable() throws Exception { 
    this.getLogger().log(Level.INFO, "Loading up!"); 
    IRCBotMain.main(null); 
} 

注:第二種方法可能不是因爲重寫onEnable()方法可能不聲明拋出異常的亞軍。

這些將避免您遇到的編譯錯誤,但是調用另一個類的主要方法有點不尋常。通常,一個main方法將成爲Java應用程序的入口點,所以它可以由Java應用程序啓動。您在問題中使用的呼叫模式表明應用程序的一部分通過main方法調用另一部分。這將是更常見的通過調用IRCBotMain非靜態,非主要的方法來做到這一點,例如

IRCBotMain bot = new IRCBotMain(); 
bot.run(); 
+0

我已經完成了這個工作。謝謝,但請再看看我的問題,我已經編輯了我現在得到的錯誤。 – Xmair

+0

這個類:'org.jibble.pircbot.PircBot'不在你的類路徑中。從[here](http://www.jibble.org/files/pircbot-1.5.0.zip)下載pircbot發行版解壓縮JAR文件並將其添加到您的類路徑中。 – glytching

+0

我已經添加了它,刪除了它,並添加了你給的一個,但我面臨着同樣的錯誤(https://pastebin.com/qvLQg3Pf)。 https://i.imgur.com/ldbqzgd.png – Xmair

0

這是不好調用另一個類的主要方法,它是可能的,你唯一需要在onEnable的方法簽名中添加'throws Exception'。

public class Main extends JavaPlugin 
{ 
    @Override 
    public void onEnable throws Exception() 
    { 
     this.getLogger().log(Level.INFO, "Loading up!"); 
     IRCBotMain.main(null); 
    } 
} 
0

你必須處理的調用方法

public static void main(String[] args) throws Exception拋出異常引發的異常。但調用方法main的方法不處理異常。

在try-catch塊把主要將工作

public void onEnable() 
{ 
    this.getLogger().log(Level.INFO, "Loading up!"); 
    try{ 
    IRCBotMain.main(null); 
    }catch(Exception e){ 
     // handle exception 
    } 
}