gpt4 book ai didi

java - 在这里使用@lombok.Cleanup的正确方法是什么?

转载 作者:行者123 更新时间:2023-12-01 20:17:57 27 4
gpt4 key购买 nike

之前的代码是这样的 -

    try {
some other code
......
......
ByteArrayInputStream annoBais = new ByteArrayInputStream(annoBytes);
DataInputStream dis = new DataInputStream(annoBais);
InputStream annoStream = dis;
inputRecord.put("XMLStream", annoStream);
MappedRecord resultMappedRecord = (MappedRecord)interaction.execute(interactionSpec,inputRecord);
HashMap mappedAnnotIds = (HashMap)resultMappedRecord.get(("ResultHashMap").toString());
annoStream.close(); //closed here
annoBais.close(); // closed here
dis.close(); // closed here
......
......
some more code
}

我把它改为-

 try {
some other code
......
......
@lombok.Cleanup ByteArrayInputStream annoBais = new ByteArrayInputStream(annoBytes);
@lombok.Cleanup DataInputStream dis = new DataInputStream(annoBais);
@lombok.Cleanup InputStream annoStream = dis;
inputRecord.put("XMLStream", annoStream);
MappedRecord resultMappedRecord (MappedRecord)interaction.execute(interactionSpec,inputRecord);
HashMap mappedAnnotIds = (HashMap)resultMappedRecord.get(("ResultHashMap").toString());
......
......
some more code
}

@lombok.Cleanup 是否具有相同的范围?它会在先前手动关闭的同一位置关闭吗?如果不是,我怎样才能以仍然具有相同范围的方式关闭它?

最佳答案

这里使用@lombok.Cleanup的正确方法是不使用lombok; Java7 通过 try with resources 解决了这个问题.

例如,使用您的代码:

     some other code
......
......

try ( ByteArrayInputStream annoBais = new ByteArrayInputStream(annoBytes);
DataInputStream dis = new DataInputStream(annoBais) ) {
InputStream annoStream = dis;
inputRecord.put("XMLStream", annoStream);
MappedRecord resultMappedRecord = (MappedRecord)interaction.execute(interactionSpec,inputRecord);
HashMap mappedAnnotIds = (HashMap)resultMappedRecord.get(("ResultHashMap").toString());
}
// annoBais & dis get closed here.
// Note: annoStream is an alias of dis, not a separate resource.
......
......
some more code

当然,这段代码需要被 try {} catch () {} block 包围,或者您的方法必须声明它抛出所需的异常。

使用“尝试使用资源”不会导致您必须处理其他异常。您始终需要处理所有已检查的异常,方法是捕获它们或声明您的方法抛出它们。

关于java - 在这里使用@lombok.Cleanup的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45442193/

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