try-with-resources 语法简介

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了try-with-resources 语法简介相关的知识,希望对你有一定的参考价值。

try-with-resources 语法特点

资源说明头()中可以包含多个定义,用分号隔开(最后的分号可以省略)。资源说明头()中定义的每个对象都会在try块的末尾调用其close()。 try-with-resources的try块可以独立存在,没有catch或finally都行。 实现了AutoCloseable的类都可以使用try-with-resources。 资源说明头()中对象的close()方法调用与创建对象的顺序相反。

案例展示

/**
 * @author 谢阳
 * @version 1.8.0_131
 * @date 2023/1/10 10:51
 * @description
 */
public class TryWithResources 
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, InstantiationException 

        try (
                First first = new First();
                Second second = new Second();
                Third third = new Third()
        ) 
            First.showState();
            Second.showState();
            Third.showState();
            System.out.println("----------------------------------------------");
        
        System.out.println("----------------------------------------------");
        First.showState();
        Second.showState();
        Third.showState();
    



class MyCloseable implements AutoCloseable 
    @Override
    public void close() 
        // 通过反射修改close的值
        try 
            Field field = this.getClass().getDeclaredField("close");
            field.setAccessible(true);
             /*
              setXXX 只适用于基础类,如果对象的字段是包装类采用set(Object obj, Object value)
             */
            field.setBoolean(this.getClass().newInstance(), true); 
         catch (Exception e) 
            e.printStackTrace();
        
        System.out.println(this.getClass().getSimpleName() + "\\tuse close()");
    



class First extends MyCloseable 
    protected static boolean close = false;

    public static void showState() 
        System.out.println(First.class.getSimpleName() + "\\tclose = " + close);
    



class Second extends MyCloseable 
    protected static boolean close = false;

    public static void showState() 
        System.out.println(Second.class.getSimpleName() + "\\tclose = " + close);
    


class Third extends MyCloseable 
    protected static boolean close = false;

    public static void showState() 
        System.out.println(Third.class.getSimpleName() + "\\tclose = " + close);
    

控制台输出

以上是关于try-with-resources 语法简介的主要内容,如果未能解决你的问题,请参考以下文章

try-with-resources

java 7 try-with-resource 语法错误

深入理解 Java try-with-resource 语法糖

Java进阶知识点3:更优雅地关闭资源 - try-with-resource语法

使用try-with-resource优雅关闭资源

java try-with-resource语句使用