class Foo { static java.util.Hashtable lookup; private static interface HANDLER_FUNC_T { public void handlerFunc(); } static { lookup = new java.util.Hashtable(); lookup.put("CONNECT", new HANDLER_FUNC_T() { public void handlerFunc() { System.out.println("CONNECT"); } }); lookup.put("TERMINATE", new HANDLER_FUNC_T() { public void handlerFunc() { System.out.println("TERMINATE"); } }); lookup.put("GET", new HANDLER_FUNC_T() { public void handlerFunc() { System.out.println("GET"); } }); // etc. } public static void main(String[] argv) { ((HANDLER_FUNC_T) lookup.get(argv[0])).handlerFunc(); } }
Dieses Codesegment leistet inhaltlich das Selbe wie das nachfolgende C Programm:
/* define a new type as a pointer to a void function, that returns a void */ typedef void (*HANDLER_FUNC_T) (void) ; typedef LOOKUP_T struct { char *msgString ; HANDLER_FUNC_T handlerFunc ; } ; static LOOKUP_T level0[] = { { "CONNECT", HandleConnect}, /* this should always be the 1st entry */ { "TERMINATE", HandleTerminate}, { "GET", HandleGet}, { "PUT", HandlePut}, { "ACTION", HandleAction}, { NULL, NULL} /* this MUST be the last entry */ } ; int ActionString( char *string) { int i, done = 0 ; /* lets loop through the table */ while( level0[ i].msgString != NULL && done == 0) { /* check match */ if( strcmp( string, level0[ i].msgString) == 0) { done = 1 ; /* show done */ (level0[ i].handler_func)() ; /* call the handler method */ } i++ ; /* point to next message */ } return done }