2017-09-26 97 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 
    } 
} 
相关问题