Java7Trywithresources-try子句中可以包含什么
我知道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子句中直
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编辑。