如何忽略IntelliJ中特定行的‘未用try-with-resources使用AutoCloseable’警告?
问题:JUnit测试中如何忽略IntelliJ对特定行的AutoCloseable资源检查
我有一个JUnit测试套件,使用了若干AutoCloseable资源,通过org.junit.jupiter.api.AfterAll注解在所有测试执行完成后关闭这些资源,示例代码如下:
class Tests { static MyCloseable[] myCloseables = new MyCloseable[3]; static class MyCloseable implements java.lang.AutoCloseable{ public void close(){} public void doStuff(){} } @BeforeAll static void setup() { for (int i = 0; i < myCloseables.length; ++i){ myCloseables[i] = new MyCloseable(); } } @Test void test1() { assertDoesNotThrow(myCloseables[0]::doStuff); } @Test void test2() { assertDoesNotThrow(myCloseables[0]::doStuff); } @AfterAll static void cleanUp() { for (MyCloseable myCloseable : myCloseables) myCloseable.close(); } }
在setup()方法的for循环体中,IntelliJ给出警告:'MyCloseable' used without 'try'-with-resources statement,但我的测试逻辑正确,后续会妥善关闭资源,请问能否仅针对报错的特定行抑制/忽略该代码检查?
解决方案
可以针对特定行精准抑制该警告,常用方式如下:
- 单行注释抑制:在触发警告的代码行上方添加
//noinspection resource注释,仅对当前行生效:
for (int i = 0; i < myCloseables.length; ++i){ //noinspection resource myCloseables[i] = new MyCloseable(); }
IDE界面快速操作:点击警告行的黄色提示标记,选择「Suppress for statement」,IDE会自动生成抑制注释,无需手动编写。
方法级注解抑制:如果需要忽略整个方法内的同类警告,可在
setup()方法上添加@SuppressWarnings("resource")注解,但这种方式范围更广,不如单行注释精准。
内容的提问来源于stack exchange,提问作者pochopsp
相关产品推荐
相关产品推荐

