gpt4 book ai didi

java - 即使函数签名抛出它,编译器也会提示未处理的 IOException

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

我有一个类,其中静态工厂方法使用 computeIfAbsent()返回一个实例:

public class TrafficMonitor {
private static ConcurrentMap<String, TrafficMonitor> instances = new ConcurrentHashMap<>();
private String busNumber;

//private constructor could throw an IOException
private TrafficMonitor(String busNumber) throws IOException {
this.busNumber = busNumber;
// it needs to be in constructor because it call a 3rd party API to instantiate an object which throws IOException
doIoOperation();
}

// static factory method to return a instance of this class
public static TrafficMonitor forBus(String busNumber) throws IOException {
// Compiler error: Unhandled exception: java.io.IOException
return instances.computeIfAbsent(busNumber, TrafficMonitor::new);
}

}

静态工厂函数中私有(private)构造函数抛出 IOException forBus(String busNumber)即使我有 throws IOException在签名中,编译器仍然提示 unhandled exception: java.io.IOException 。为什么?如何摆脱它?

另一个问题:在这个例子中, TrafficMonitor::new 是吗?自动获取参数busNumber来自forBus(String busNumber)函数或者它如何使用需要参数的私有(private)构造函数创建实例 String busNumber

最佳答案

computeIfAbsent 需要一个 Function 作为参数。 Function的SAM的签名是R apply(T t)。如您所见,Function 可能不会抛出 IOException。但您的构造函数确实会抛出 IOException。所以 TrafficMonitor::new 不是一个函数。因此,您不能将其作为参数传递给 computeIfAbsent()

干净的方式:不要在构造函数中执行 IO:

public class TrafficMonitor {
private static ConcurrentMap<String, TrafficMonitor> instances = new ConcurrentHashMap<>();
private String busNumber;
private boolean initialized;

private TrafficMonitor(String busNumber) {
this.busNumber = busNumber;
}

private synchronized void initialize() throws IOException {
if (!initialized) {
doIoOperation();
initialized = true;
}
}

public static TrafficMonitor forBus(String busNumber) throws IOException {
TrafficMonitor result = instances.computeIfAbsent(busNumber, TrafficMonitor::new);
result.initialize();
return result;
}
}

不太干净的方法:将 IOException 作为运行时异常重新抛出

private TrafficMonitor(String busNumber) {
this.busNumber = busNumber;
try {
doIoOperation();
} catch(IOException e) {
throw UnchedkIOException(e);
}
}

public static TrafficMonitor forBus(String busNumber) {
return instances.computeIfAbsent(busNumber, busNumber -> {
try {
return new TrafficMonitor(busNumber);
} catch(IOException e) {
throw UnchedkIOException(e);
}
});
}

关于java - 即使函数签名抛出它,编译器也会提示未处理的 IOException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58366164/

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