Lombok之@Cleanup使用

mac2024-05-12  39

一. 为什么要用@Cleanup?

在IO流的学习中,每次都要在finally里面关闭资源,是不是很让人头疼?那么有没有好的方法去生成这样的重复代码。方法有两种:一种是使用Lombok的@Cleanup,另一种是使用jdk1.7+的try-with-resources语法糖。我个人推荐使用try-with-resources语法糖,因为它是jdk提供的,所以受众更广,别人能更容易读懂你的代码,也不用绑定插件才能使用。在关闭流(资源)的时候,经常使用到以下代码

try { // to do something }finally { if (in != null) { in.close(); } }

这样的代码,如同模板一样,出现在程序各个地方。下面演示两种方法是如何自动关闭流的。

二. @Cleanup如何使用?

public class CleanupExample { public static void main(String[] args) throws IOException { try(InputStream inputStream = new FileInputStream(".\\src\\main\\java\\com\\cauchy6317\\common\\Cleanup\\ForCleanupExample.txt")){ // to do something } @Cleanup Reader fileReader = new FileReader(".\\src\\main\\java\\com\\cauchy6317\\common\\Cleanup\\ForCleanupExample1.txt"); // to do something } }

第一种是try-with-resources语法糖,在try后面初始化流,可以同时初始化多个。第二种是@Cleanup注解模式。 从反编译的代码来看,@Cleanup更简洁些。它使用了“Collections.singletonList(fileReader).get(0) != null”进行资源对象fileReader的判空,我不知道这样做有什么好处(哪位前辈能解释一下,十分感谢)。还有,在try-with-catch语法糖中生成的“Object var2 = null;”也不清楚用意何在。

三. @Cleanup源码

@Target(ElementType.LOCAL_VARIABLE) @Retention(RetentionPolicy.SOURCE) public @interface Cleanup { /** @return The name of the method that cleans up the resource. By default, 'close'. The method must not have any parameters. */ String value() default "close"; }

注解属性:value,也是我觉得Lombok比较好的一点,它可以指定关闭方法的方法名。

四. 特别说明

本文已经收录在Lombok注解系列文章总览中,并继承上文中所提的特别说明。 源码地址:gitee

最新回复(0)