gpt4 book ai didi

java - 从 Java 1.7 到 Java 1.6 的“try catch”重构

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

我使用的是别人的jar文件,但我需要将源代码添加到我的项目中并在导入此类包时编译它们。问题是这个 jar 文件似乎是由 java1.7 生成的,所以它使用了一些 java1.7 特性。但是我使用的是 java1.6。对于此源代码:

public Properties getDefaults() {
try (InputStream stream
= getClass().getResourceAsStream(PROPERTY_FILE)) {

Properties properties = new Properties();
properties.load(stream);
return properties;

} catch (IOException e) {
throw new RuntimeException(e);

}
}

eclipse给出了这样的错误提示:

Resource specification not allowed here for source level below 1.7

那我要如何重写这样的代码才能被java1.6处理呢?

最佳答案

要重新编写与 Java 1.6 兼容的 try-with-resource 语句,请执行以下操作:

  • try block 开始之前声明变量。
  • try block 的顶部创建变量。
  • 添加一个 finally block 来关闭资源。

例子:

InputStream stream = null;
try
{
stream = getClass().getResourceAsStream(PROPERTY_FILE));
// Rest of try block is the same
}
// catch block is the same
finally
{
if (stream != null)
{
try {
stream.close();
} catch (IOException ignored) { }
}
}

关于java - 从 Java 1.7 到 Java 1.6 的“try catch”重构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26917141/

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