lombok 基础注解之 @Cleanup

最全的 lombok 注解详情(随着版本不定时更新)

一、注解介绍

作用于变量,自动关闭资源,仅针对实现了 java.io.Closeable 接口的对象有效

二、属性介绍

  • value:指定的方法(这个方法需要在注解对象中存在)关闭资源,默认使用 close 方法
    如果指定的方法带异常,则需要捕获或者抛出该异常(可以比该异常大)

三、实战演练

public class 景甜 {
    
    
	public static void main(String[] args) {
    
    
		@Cleanup Scanner scanner = new Scanner(System.in);
		try {
    
    
			@Cleanup Reader reader = new FileReader(new File(""));
		} catch (FileNotFoundException e) {
    
    
			e.printStackTrace();
		} catch (IOException e) {
    
    
			e.printStackTrace();
		}
	}
}
编译后
public class 景甜 {
    
    
	public static void main(String[] args) {
    
    
    	Scanner scanner = new Scanner(System.in);
    	try {
    
    
      		try {
    
    
      			Reader reader = new FileReader(new File(""));
      			if (Collections.singletonList(reader).get(0) != null) reader.close();
      		} catch (FileNotFoundException e) {
    
    
       			 e.printStackTrace();
      		} catch (IOException e) {
    
    
        		e.printStackTrace();
      		}
      		if (Collections.singletonList(scanner).get(0) == null) return; scanner.close();
      	} finally {
    
    
      		if (Collections.singletonList(scanner).get(0) != null) scanner.close();
    	}
  	}
}

猜你喜欢

转载自blog.csdn.net/qq_39249094/article/details/120881660