为了理解finally块的行为,我编写了七个测试用例。finally如何工作背后的逻辑是什么?
package core;
public class Test {
public static void main(String[] args) {
new Test().testFinally();
}
public void testFinally() {
System.out.println("One = " + tryOne());
System.out.println("Two = " + tryTwo());
System.out.println("Three = " + tryThree());
System.out.println("Four = " + tryFour());
System.out.println("Five = " + tryFive());
System.out.println("Six = " + trySix());
System.out.println("Seven = " + trySeven());
}
protected StringBuilder tryOne() {
StringBuilder builder = new StringBuilder();
try {
builder.append("Cool");
return builder.append("Return");
}
finally {
builder = null;
}
}
protected String tryTwo() {
String builder = "Cool";
try {
return builder += "Return";
}
finally {
builder = null;
}
}
protected int tryThree() {
int builder = 99;
try {
return builder += 1;
}
finally {
builder = 0;
}
}
protected StringBuilder tryFour() {
StringBuilder builder = new StringBuilder();
try {
builder.append("Cool");
return builder.append("Return");
}
finally {
builder.append("+1");
}
}
protected int tryFive() {
int count = 0;
try {
count = 99;
}
finally {
count++;
}
return count;
}
protected int trySix() {
int count = 0;
try {
count = 99;
}
finally {
count = 1;
}
return count;
}
protected int trySeven() {
int count = 0;
try {
count = 99;
return count;
}
finally {
count++;
}
}
}为什么builder = null不能工作?
为什么builder.append("+1")工作,而count++(在trySeven()中)不工作?
发布于 2010-07-12 05:57:21
为什么builder = null不能工作?
因为要将本地引用设置为null,因此不会更改内存的内容。因此,它是工作的,如果您试图在最后块之后访问构建器,那么您将获得null。
为什么builder.append("+1") work?
因为您正在使用引用修改内存的内容,这就是它应该工作的原因。
为什么count++不能在testFive()中工作?
对我来说很好。它的产出如预期的那样为100。
https://stackoverflow.com/questions/3226100
复制相似问题