[英]Java: startingPath as “public static final” exception
[已更新,对更改感到抱歉,但现在是真正的问题]对于getCanonicalPath()方法中的异常,我无法在其中包括try-catch-loop。 我试图通过方法来解决问题,然后在其中声明值。 问题是它是最终版本,我无法更改。 因此,如何将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
您可以提供一个静态方法来初始化您的静态变量:
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
因此没有办法声明抛出的异常。 仅供参考,如果变量是非static
,则可以通过在构造函数中声明抛出的异常来做到这一点,如下所示:
public class PathHandler {
private final String thePath = new File(".").getCanonicalPath();
public PathHandler() throws IOException {
// other initialization
}
这个名字很好。 您忘记声明类型了。
public static final String startingPath;
// ^^^^^^
修复此问题,您当然会认识到如何处理可能的IOException
和startingPath
是final
难题。 一种方法是使用static
初始化程序:
在初始化类时,将执行在类中声明的任何静态初始化器,并且可以将其与任何用于类变量的字段初始化器一起用于初始化该类的类变量。
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中推荐的方法。
只需在静态块中对其进行初始化(变量为final)。 您不能在声明变量时捕获异常。
您缺少变量的类型,应该是
public static void String startingPath ...
public static final String startingPath = (new File(".")).getCanonicalPath();
你缺少变量的类型startingPath
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.