0

我在使用默认构造函数的参数调用构造函数时遇到问题。

   Class A {            
             private static Properties properties;

             A(Properties property){

                 // do some checks
                    try{
                      load(property, fileName)
                     } catch(IOException e) {
                       throw new RuntimeException();
                     }
                 }

             A(){
                   this(load(properties));
                }

            private static Properties load(Properties properties, String fileName ) throws IOException {
               try {
                    properties.load(A.class.getClassLoader()
                            .getResourceAsStream(fileName));
                   } catch (IOException ioException) {
                    throw new IOException("Unable to process the properties File. " + fileName, ioException);
                  }

                return properties;
             }
    }

我的问题是:在默认构造函数中,我想使用 try/catch 块并执行抛出运行时异常的相同操作。你能帮我解决这个问题吗?

WRT这篇文章:在Java中链接构造函数而不从默认构造函数中抛出异常

我可以选择将 try/catch 放入另一个方法中。但是有没有别的办法?PS:我不想使用“投掷”

4

2 回答 2

0

Java 不允许将链式构造函数调用包含在try块中,因为如果不受限制,此类构造可能允许其基对象引发异常的对象最终返回给调用代码。这使得表达某些涉及文件等资源的概念变得困难[例如,让构造函数在链接到父级之前打开文件并在之后关闭它会很有帮助,但是没有办法安全地让构造函数对文件负责在链接到父级之前打开]。在 Java 中可以做的最好的事情是避免可能抛出异常的公共构造函数,而是使用可以更好地处理它们的工厂方法。

于 2013-11-05T01:48:18.720 回答
-1

选项 1:向另一个构造函数传递一个新的属性空实例:

class A
{ 
  public A()
  {
    this(new Properties());
  }

  // rest of code...
}

选项 2:将属性的空实例传递给其他构造函数。然后你必须防止 null in load(...),但你可能应该是:

class A
{ 
  public A()
  {
    this(null);
  }

  // rest of code...
}

选项 3:向其他构造函数传递属性的默认实例:

class A
{
  private static final Properties defaultProperties;
  static
  {
     defaultProperties = new Properties();
     // populate here however you wish
  }

  public A()
  {
    this(defaultProperties);
  }

  // rest of code...
}
于 2013-11-04T17:58:32.113 回答