Code sample sharing that illustrates Java's pass back mechanism

  • 2020-04-01 04:11:24
  • OfStack

Java pass value or pass reference
1. Original type parameter passing


public void badSwap(int var1, int var2)  
{ 
int temp = var1;  
var1 = var2;  
var2 = temp; 
} 

2. Reference type parameter passing


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); 
} 

Run the two programs, I believe you will understand: Java manipulates objects' by reference, 'but it passes the object references to the methods' by value.


Java callback mechanism
Spring makes extensive use of Java callback mechanism. Here is a brief introduction to Java callback mechanism:

In a word, a callback is a two-way invocation pattern, which means that the caller will also call the other party when it is called. This is called a callback. "If you call me, I will call back."

See the following example of a callback mechanism:

Interface CallBackInterface:


public interface CallBackInterface {
 void save();
}

Class ClassB:


public class ClassB implements CallBackInterface {

public void save() {
System.out.println(" Perform a save operation !");
}
//
public void add()
{

    //This calls the ClassA method and ClasssB calls back the ClassB save method
    new ClassA().executeSave(new ClassB());
 }

}

Class ClassA:


public class ClassA {

 public void executeSave(CallBackInterface callBackInterface)
 {
 getConn();
 callBackInterface.save();  //you call me
 realse();
 }
 public void getConn()
 {
 System.out.println(" Getting a database connection !");
 }
 public void realse()
 {
 System.out.println(" Release database connection !");
 }
}

The more classic example of using callback functions (using Java anonymous classes) is where the source code is omitted


Related articles: