簡體   English   中英

Java:startingPath作為“公共靜態最終”異常

[英]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;
//                  ^^^^^^

修復此問題,您當然會認識到如何處理可能的IOExceptionstartingPathfinal難題。 一種方法是使用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中推薦的方法。


也可以看看

只需在靜態塊中對其進行初始化(變量為final)。 您不能在聲明變量時捕獲異常。

您缺少變量的類型,應該是

public static void String startingPath ...
 public static final String startingPath = (new File(".")).getCanonicalPath();

你缺少變量的類型startingPath

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM