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
我怎麼能解決這個問題,因爲它出現在該行,其中元素被定義,而不是一個方法?
的可能的複製[如何從一個枚舉拋出一個異常構造函數?(http://stackoverflow.com/questions/3543903/how-to-throw-an-exception-from-an-enum-constructor) – wero