0

[已更新,对更改感到抱歉,但现在是真正的问题] 我不能在其中包含 try-catch-loop 以用于方法 getCanonicalPath() 的异常。我试图用方法更早地解决问题,然后在那里声明值。问题是它是最终的,我无法更改它。那么如何将startingPath设置为“public static final”。

$ cat StartingPath.java 
import java.util.*;
import java.io.*;

public class StartingPath {
 public static final String startingPath = (new File(".")).getCanonicalPath();

 public static void main(String[] args){
  System.out.println(startingPath);
 }
}
$ javac StartingPath.java 
StartingPath.java:5: unreported exception java.io.IOException; must be caught or declared to be thrown
 public static final String startingPath = (new File(".")).getCanonicalPath();
                                                                           ^
1 error
4

5 回答 5

5

您可以提供一个静态方法来初始化您的静态变量:

public static final String startingPath = initPath();

private static String initPath() {
    try {
        return new File(".").getCanonicalPath();
    } catch (IOException e) {
        throw new RuntimeException("Got I/O exception during initialization", e);
    }
}

或者您可以在静态块中初始化变量:

public static final String startingPath;

static {
    try {
        startingPath = new File(".").getCanonicalPath();
    } catch (IOException e) {
        throw new RuntimeException("Got I/O exception during initialization", e);
    }
}

编辑:在这种情况下,你的变量是static所以没有办法声明抛出的异常。仅供参考,如果变量是 non-static你可以通过在构造函数中声明抛出的异常来做到这一点,如下所示:

public class PathHandler {

    private final String thePath = new File(".").getCanonicalPath();

    public PathHandler() throws IOException {
        // other initialization
    }
于 2010-04-10T16:06:17.873 回答
4

名字不错;你忘了声明类型。

public static final String startingPath;
//                  ^^^^^^

解决这个问题,你当然会意识到如何处理可能IOExceptionstartingPath存在的更难的问题final。一种方法是使用static初始化器:

JLS 8.7 静态初始化器

类中声明的任何静态初始化程序都会在类初始化时执行,并且可以与类变量的任何字段初始化程序一起用于初始化类的类变量。

 public static final String startingPath;
 static {
    String path = null;
    try {
      path = new File(".").getCanonicalPath();
    } catch (IOException e) {
      // do whatever you have to do
    }
    startingPath = path;
 }

另一种方法是使用一种static方法(参见Kevin Brock 的回答)。这种方法实际上会带来更好的可读性,并且是 Josh Bloch 在Effective Java中推荐的方法。


也可以看看

于 2010-04-10T15:57:06.573 回答
2

Just initialize it in the static block(the variable is final). You can't catch exceptions on declaring a variable.

于 2010-04-10T16:04:11.843 回答
0

您缺少变量的类型,应该是

public static void String startingPath ...
于 2010-04-10T15:57:47.900 回答
0
 public static final String startingPath = (new File(".")).getCanonicalPath();

您缺少变量的类型 startingPath

于 2010-04-10T15:57:50.973 回答