java傳值還是傳引用
1.原始類型參數(shù)傳遞
1
2
3
4
5
6
|
public void badSwap( int var1, int var2) { int temp = var1; var1 = var2; var2 = temp; } |
2.引用類型參數(shù)傳遞
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
public void tricky(Point arg1, Point arg2) { arg1.x = 100 ; arg1.y = 100 ; Point temp = arg1; arg1 = arg2; arg2 = temp; } public static void main(String [] args) { Point pnt1 = new Point( 0 , 0 ); Point pnt2 = new Point( 0 , 0 ); System.out.println( "X: " + pnt1.x + " Y: " +pnt1.y); System.out.println( "X: " + pnt2.x + " Y: " +pnt2.y); System.out.println( " " ); tricky(pnt1,pnt2); System.out.println( "X: " + pnt1.x + " Y:" + pnt1.y); System.out.println( "X: " + pnt2.x + " Y: " +pnt2.y); } |
運(yùn)行這兩個(gè)程序,相信你會(huì)明白的:Java manipulates objects 'by reference,' but it passes object references to methods 'by value.
java回調(diào)機(jī)制
spring大量使用了java回調(diào)機(jī)制,下面對(duì)Java回調(diào)機(jī)制做一些簡(jiǎn)單的介紹:
一句話,回調(diào)是一種雙向調(diào)用模式,什么意思呢,就是說(shuō),被調(diào)用方在被調(diào)用時(shí)也會(huì)調(diào)用對(duì)方,這就叫回調(diào)。“If you call me, i will call back”。
看下面關(guān)于回調(diào)機(jī)制的例子:
接口CallBackInterface :
1
2
3
|
public interface CallBackInterface { void save(); } |
類ClassB:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public class ClassB implements CallBackInterface { public void save() { System.out.println( "執(zhí)行保存操作!" ); } // public void add() { //這里調(diào)用ClassA的方法 同時(shí)ClasssB又會(huì)回調(diào)ClassB的save方法 new ClassA().executeSave( new ClassB()); } } |
類ClassA:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class ClassA { public void executeSave(CallBackInterface callBackInterface) { getConn(); callBackInterface.save(); //you call me realse(); } public void getConn() { System.out.println( "獲取數(shù)據(jù)庫(kù)連接!" ); } public void realse() { System.out.println( "釋放數(shù)據(jù)庫(kù)連接!" ); } } |
更加經(jīng)典的關(guān)于回調(diào)函數(shù)的使用的例子(使用java匿名類)這里省去了源碼