0

我想用它的构造函数在方法之外实例化一个对象。例子:

public class Toplevel {

   Configuration config = new Configuration("testconfig.properties");

   public void method1() {

      config.getValue();
      ...etc
   }
}

如果我现在这样做......我得到这个错误..

Default constructor cannot handle exception type IOException thrown by implicit super constructor. Must define an explicit constructor

我想做这样的事情,这样我就可以在课堂上的任何地方调用 config,现在我不得不实例化配置对象......必须有办法做到这一点......任何帮助将不胜感激,提前致谢。

编辑:

配置类:

public class Configuration {

private String mainSchemaFile;


public Configuration() {
}

public Configuration( String configPath ) throws IOException {

    Properties prop = new Properties();
    prop.load( new FileInputStream( configPath ));

    this.mainSchemaFile= prop.getProperty("MAINSCHEMA_FILE");
}
4

2 回答 2

2

您的Configuration构造函数被声明为抛出一个IOException. 任何Configuration使用此构造函数实例化 a 的代码都必须捕获它。如果您使用变量初始化器,那么您将无法捕获它,因为您无法提供catch块;没有可以放在这里的块,只有一个表达式。没有任何方法可以声明任何一个throws子句。

您的替代方案:

  • ConfigurationToplevel构造函数中实例化。您可以catch在构造函数主体中出现异常,或者您可以将该构造函数声明throws为异常。

    public class Toplevel {
        Configuration config;
        public Toplevel() {
            try {
                config = new Configuration("testconfig.properties");
            } catch (IOException e) {  // handle here }
        }
        // ...
    
  • 在类中实例化Configuration一个实例初始化器TopLevel,您可以catch在其中处理异常并处理它。

    public class Toplevel {
        Configuration config;
    
        {
            try {
                config = new Configuration("testconfig.properties");
            } catch (IOException e) {  // handle here }
        }
        // ...
    
  • 在构造函数中捕获并处理异常Configuration,因此调用代码不必捕获异常。这不是首选,因为您可能实例化了无效Configuration对象。调用代码仍然需要确定它是否有效。

    public class Configuration {
         // Your instance variables
         private boolean isValid;
    
         public Configuration( String configPath )  {
             try {
                 // Your code that might throw an IOE
                 isValid = true;
             } catch (IOException e) {
                 isValid = false;
             }
         }
    
于 2015-07-22T19:11:14.520 回答
1

当您创建一个新的 Toplevel 对象时,您还没有为它声明一个特定的构造函数,并且 Toplevel 的属性被实例化为您的代码描述它Configuration config = new Configuration("testconfig.properties");

所以你不处理 Configuration 构造函数的 IoException !更好的方法是像这样声明 Toplevel 的特定构造函数:

public Toplevel(){
    try{
        this.config = new Configuration("testconfig.properties");
    } catch (IOException e) {
        // handle Exception
    }
}
于 2015-07-22T19:14:20.917 回答