Personal understanding: The callback function is to throw part of the implementation to the customer
Package com.cy.test;
Import java.util.ArrayList;
Import Java.util.Arrays;
Import java.util.List;
public class Workimpl {public
void work (CallBack CallBack) {
System.out.println ("Work start ...");
list<string> list = new arraylist<string> ();
List.add ("1");
List.add ("2");
List.add ("3");
Callback.execute (list);
System.out.println (Arrays.tostring (List.toarray ()));
}
public static void Main (string[] args) {
Workimpl work = new Workimpl ();
Work.work (New CallBack () {public
void execute (list<string> List) {
list.add ("haha");
}
);
}
}
Interface CallBack {
void execute (list<string> List);
}
Here's an example:
Package com.cy.test;
Import java.io.*;
/** * Example of callback function when uploading files * * public class Uploadservice {public void upload (Uploadcallback callback) throws Exception {
File F = new file ("Tmp-test.txt");
FileOutputStream out = new FileOutputStream (f);
Callback.send (out); public static void Main (string[] args) throws Exception {Uploadservice uploadservice = new Uploadservice ()
;
InputStream in = null;
The callback interface enables a more flexible//1-provided reference implementation of 1 uploadservice.upload (new Uploadstream (in));
2 provides the parameter implementation 2 Uploadservice.upload ("The New Uploadlocalfile" ("File")); 3.//4 Use yourself to implement Uploadservice.upload (new Uploadcallback () {public void Send (outputstre
Am out) throws IOException {//...}
});
}/** * Callback interface * * Interface Uploadcallback {void send (OutputStream out) throws IOException; /** * Callback implemented via IO Stream/class Uploadstream implements Uploadcallback {inputstream in;
Public Uploadstream (InputStream in) {this.in = in;
public void Send (OutputStream out) throws IOException {int readbytes;
byte[] Buff = new byte[256 * 1024]; try {while (Readbytes=in.read (buff)) >= 0) {if (readbytes = = 0) {Co
Ntinue;
} out.write (Buff, 0, readbytes);
finally {in.close ();
}}/** * callback implemented via local file */class Uploadlocalfile implements Uploadcallback {private String local_filename;
Public Uploadlocalfile (String szlocalfilename) {this.local_filename = Szlocalfilename;
public void Send (OutputStream out) throws IOException {FileInputStream fis;
int readbytes;
byte[] Buff = new byte[256 * 1024];
FIS = new FileInputStream (this.local_filename); try {while (readbytes = Fis.reaD (Buff)) >= 0 {if (readbytes = = 0) {continue;
} out.write (Buff, 0, readbytes);
finally {fis.close (); }
}
}