try-with-resources 语法简介

时间:2023-01-10 19:04:15

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 语法简介