Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java7Trywithresources-try子句中可以包含什么_Java_Try Catch - Fatal编程技术网

Java7Trywithresources-try子句中可以包含什么

Java7Trywithresources-try子句中可以包含什么,java,try-catch,Java,Try Catch,我知道try子句中必须有一个与资源关联的变量声明 但是,除了分配一个普通的资源实例化之外,它是否可以被分配一个已经存在的资源,例如: public String getAsString(HttpServletRequest request) throws Exception { try (BufferedReader in = request.getReader(); ){ etc } } 也就是说,BufferedReader是否会像try子句中直

我知道try子句中必须有一个与资源关联的变量声明

但是,除了分配一个普通的资源实例化之外,它是否可以被分配一个已经存在的资源,例如:

public String getAsString(HttpServletRequest request) throws Exception {   
    try (BufferedReader in = request.getReader(); ){ 
        etc 
    } 
}

也就是说,
BufferedReader
是否会像try子句中直接实例化的资源一样自动关闭?

Yes。任何可自动关闭的
都将调用
close
方法。使用资源进行尝试可以做到这一点

。任何可自动关闭的
都将调用
close
方法。使用资源进行尝试可以做到这一点

我们可以使用以下代码测试这是否正确:

class Main {
    public static void main(String[]args) throws Exception {
        AutoCloseable _close = getCloseable()
       try (AutoCloseable close = _close) {
           // ...
       }

    }

    public static AutoCloseable getCloseable() {
        return new MyCloseable();
    }
}

class MyCloseable implements AutoCloseable {

    @Override
    public void close() {
        System.out.println("Closing");
    }
}
输出为“关闭”。这意味着,实际上,在
try
块之前创建的
AutoCloseable
s仍将在
try
块之后关闭


实际上,Java并不关心您在
try
块的
()
中放了什么,只要它实现了
自动关闭
。在运行时,表达式将自动计算为一个值,无论它是否为
新的
表达式。

我们可以使用以下代码测试这是否正确:

class Main {
    public static void main(String[]args) throws Exception {
        AutoCloseable _close = getCloseable()
       try (AutoCloseable close = _close) {
           // ...
       }

    }

    public static AutoCloseable getCloseable() {
        return new MyCloseable();
    }
}

class MyCloseable implements AutoCloseable {

    @Override
    public void close() {
        System.out.println("Closing");
    }
}
输出为“关闭”。这意味着,实际上,在
try
块之前创建的
AutoCloseable
s仍将在
try
块之后关闭


实际上,Java并不关心您在
try
块的
()
中放了什么,只要它实现了
自动关闭
。在运行时,表达式将自动计算为一个值,无论它是否为
新的
表达式。

是,
缓冲读取器将自动关闭


自Java 7以来,接口
AutoCloseable
被添加为
Closeable
的超级接口,因此
Closeable
接口的所有实现类(即资源类)都自动继承
AutoCloseable
接口

是,
BufferedReader
将自动关闭


自Java 7以来,接口
AutoCloseable
被添加为
Closeable
的超级接口,因此
Closeable
接口的所有实现类(即资源类)都自动继承
AutoCloseable
接口

你试过吗?你的问题有点不清楚-如果你在try块中声明了一个可关闭的资源(你在那里写“etc”),它就不会被关闭。你试过吗?你的问题有点不清楚-如果你在try块中声明了一个可关闭的资源(你在那里写“etc”),它就不会被关闭。@ythonas“已经存在”到底是什么意思?我认为这意味着从上下文来看,它意味着“任何未在
()
中实例化的内容”。@andythonas Edited.@andythonas“已经存在”到底是什么意思?我认为这意味着从上下文判断,它意味着“任何未在
()
中实例化的内容”。@Andythonas编辑。