gpt4 book ai didi

java - 为什么我会收到此编译器错误(使用枚举作为单例)?

转载 作者:行者123 更新时间:2023-11-30 08:08:38 25 4
gpt4 key购买 nike

我有下面的类,里面封装了一些测试数据。我只需要它的一个实例,所以我创建了一个枚举。

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

如果它发生在定义元素而不是方法的那一行,我该如何修复它?

最佳答案

How can I fix it, given that it occurs at the line, where the element is defined, not a method?

在底层,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);
}
}

关于java - 为什么我会收到此编译器错误(使用枚举作为单例)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33053498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com