java傳值還是傳引用
1.原始類型參數傳遞
1
2
3
4
5
6
|
public void badSwap( int var1, int var2) { int temp = var1; var1 = var2; var2 = temp; } |
2.引用類型參數傳遞
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); } |
運行這兩個程序,相信你會明白的:Java manipulates objects 'by reference,' but it passes object references to methods 'by value.
java回調機制
spring大量使用了java回調機制,下面對Java回調機制做一些簡單的介紹:
一句話,回調是一種雙向調用模式,什么意思呢,就是說,被調用方在被調用時也會調用對方,這就叫回調。“If you call me, i will call back”。
看下面關于回調機制的例子:
接口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( "執行保存操作!" ); } // public void add() { //這里調用ClassA的方法 同時ClasssB又會回調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( "獲取數據庫連接!" ); } public void realse() { System.out.println( "釋放數據庫連接!" ); } } |
更加經典的關于回調函數的使用的例子(使用java匿名類)這里省去了源碼