2015-10-10 70 views
2

我有以下類,它封裝了一些測試數據。我只需要它的一個實例,所以我創建了一個枚舉。爲什麼我得到這個編譯器錯誤(使用enum作爲單例)?

public enum ErnstReuterPlatzBuildings { 
    INSTANCE; // Compiler error occurs here 
    private final Map<String, IBuilding> buildingsByIds; 
    ErnstReuterPlatzBuildings() throws ParserConfigurationException, 
     SAXException, XPathExpressionException, IOException { 
     this.buildingsByIds = composeBuildingsByIds(
      getBuildings(ErnstReuterPlatzBuildings.class) 
     ); 
    } 
    public Map<String, IBuilding> getBuildingsByIds() { 
     return buildingsByIds; 
    } 
    public static Document readErnstReuterPlatzData(final Class clazz) 
     throws ParserConfigurationException, SAXException, IOException { 
     final InputStream stream = 
      clazz.getClassLoader() 
       .getResourceAsStream("mc/ernstReuterPlatz/map.osm"); 
     final DocumentBuilderFactory dbfac = 
      DocumentBuilderFactory.newInstance(); 
     final DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); 
     return docBuilder.parse(stream); 
    } 

    private Map<String, IBuilding> composeBuildingsByIds(
     final Set<IBuilding> buildings) { 
     final Map<String,IBuilding> buildingsByIds = new HashMap<>(); 
     for (final IBuilding building : buildings) { 
      buildingsByIds.put(building.getWayId(), building); 
     } 
     return buildingsByIds; 
    } 

    private Set<IBuilding> getBuildings(final Class clazz) 
     throws ParserConfigurationException, SAXException, IOException, 
     XPathExpressionException { 
     final Document doc = readErnstReuterPlatzData(clazz); 
     final PointsReader pointsReader = new PointsReader(doc); 
     pointsReader.init(); 
     final BuildingExtractor testObject = 
      new BuildingExtractor(pointsReader); 
     return testObject.extractBuildings(doc); 
    } 
} 

在其唯一元素的聲明,INSTANCE;我得到的IntelliJ IDEA以下編譯器錯誤:

Error:(22, 5) java: unreported exception javax.xml.parsers.ParserConfigurationException; must be caught or declared to be thrown 

我怎麼能解決這個問題,因爲它出現在該行,其中元素被定義,而不是一個方法?

+0

的可能的複製[如何從一個枚舉拋出一個異常構造函數?(http://stackoverflow.com/questions/3543903/how-to-throw-an-exception-from-an-enum-constructor) – wero

回答

3

我該如何解決它,因爲它發生在線,定義的元素,而不是一個方法?

底層Java通過調用構造函數創建實例INSTANCE。聲明行上的代碼與此類似:

public static final INSTANCE = new ErnstReuterPlatzBuildings(); 

這就是錯誤來自該行的原因。

據我所知,目前還沒有辦法通過允許用戶捕捉檢查異常來解決這個問題,因爲INSTANCE是在上下文中的任何方法調用之外初始化。

可以解決此問題自己捕捉異常,並在適當類型的未查看RuntimeException甚至是ExceptionInInitializerError它包裝:

ErnstReuterPlatzBuildings() { 
    try { 
     this.buildingsByIds = composeBuildingsByIds(
      getBuildings(ErnstReuterPlatzBuildings.class) 
     ); 
    } catch (ParserConfigurationException pce) { 
     throw new ExceptionInInitializerError(pce); 
    } catch (SAXException sxe) { 
     throw new ExceptionInInitializerError(sxe); 
    } catch (XPathExpressionException xpe) { 
     throw new ExceptionInInitializerError(xpe); 
    } catch (IOException ioe) { 
     throw new ExceptionInInitializerError(ioe); 
    } 
}