public class Test {
public static void main(String[] args) {
System.out.println(test1());
System.out.println(test2());
}
public static int test1() {
int a = 10;
try {
a += 5;
return a;
} catch (Exception e) {
a += 10;
return a;
} finally {
a += 20;
}
}
public static A test2() {
A aClass = new A(10);
try {
aClass.a += 5;
return aClass;
} catch (Exception e) {
aClass.a++;
return aClass;
} finally {
aClass.b=10;
aClass.a += 20;
}
}
private static class A {
int a;
int b;
public A(int a) {
this.a = a;
}
@Override
public String toString() {
return"a=" + a + "\nb=" + b;
}
}
}
return:
15
a=35
b=10
复制代码
看到这里相信有部分童鞋可能不理解了,为什么会这样呢?在Java中有着值传递,而非引用传递这一说,简单来说,就是基本类型作为参数传递时,是传递值的拷贝,无论你怎么改变这个拷贝,原值是不会改变的,test1中先执行了一个return语句,返回栈中有了一个a,当执行到finally中时,做了a = a +· 20的操作,此时的a已经不是返回栈中的a了,a的引用发生了改变,所以不回传给返回栈中的a了,所以test1返回值是15;而对象作为参数传递时,是把对象在内存中的地址拷贝了一份传给了参数,在test2中,我们把A直接返回了,而在finally中操作的是A对象的属性,所以这样是可以成功的。
咦~怎么报错了Only the original thread that created a view hierarchy can touch its views.为什么会这样呢?不延迟就不报错,延迟了就报错。下面我们来分析一下,先找到这个错是在哪里报的,这个应该不难找吧ctrl + shift + f全部搜索一下这个报错信息,我们发现是在ViewRootImpl这个类中的checkMain方法中,刚好我们昨天分析从源码的角度浅谈Activity、Window、View之间的关系的时候有介绍过:
WindowManagerGlobal类:
public void addView(View view, ViewGroup.LayoutParams params,
Display display, Window parentWindow) {
...
ViewRootImpl root;
View panelParentView = null;
...
root = new ViewRootImpl(view.getContext(), display);
view.setLayoutParams(wparams);
mViews.add(view);
mRoots.add(root);
mParams.add(wparams);
// do this last because it fires off messages to start doing things
try {
root.setView(view, wparams, panelParentView);
} catch (RuntimeException e) {
}
...
}
复制代码
初始化完ViewRootImpl之后,会调用它的setView方法:
ViewRootImpl类:
public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
...
requestLayout();
...
}
@Override
public void requestLayout() {
if (!mHandlingLayoutInLayoutRequest) {
checkThread();
mLayoutRequested = true;
scheduleTraversals();
}
}
void checkThread() {
if (mThread != Thread.currentThread()) {
throw new CalledFromWrongThreadException(
"Only the original thread that created a view hierarchy can touch its views.");
}
}
复制代码