Tricky Tricks ›› Programming Tricks ›› Java Tricks ›› Method Pointers

Method Pointers

Java Programming Tricks

Method pointers:

One of the less safe features of C is function pointers — it is usually not possible to write generic and typesafe code with function pointers. (In C++, templates can be used to for typesafe generic code.) For example, consider qsort in the standard C library, or a callback in Windows or X Windows. These callbacks use unchecked void* parameters. For that reason, Java did not have function pointers. But they slipped into Java 1.1 with the reflection feature.

Tip

Of course, normally you would use a dynamically bound method with a known name and signature, and then use inheritance to call different functions with similar properties, But sometimes, that is too constraining. Consider this example — we want to print tables of mathematical functions.

 { double dx = (to - from) / 20; 
 
 for (double x = from; x <= to; x += dx) 
 
 { 
 
 double y = f(x); // wrong syntax 
 
 Format.print(System.out, "%12.4f |", x); 
 
 Fozmat.print(System.out, "%12.4f\n", y); 
 
 }
 
 static void printTable(double from, double to, Method f) 
 
 }
 
 printTable(0, 10, Math.sin); // wrong syntax 
 
 In principle, this is now possible in Java, but the syntax is more complex. 
 
 Here is how you can get a method pointer: 
 
 printTable(0, 10, java.lang.Math.class.getMethod("sqrt", new Class[] { double.class })); 
 
 And here is how you make the call: 
 
 static void printTable(double from, double to, Method f) 
 
 {  .  .  .
 
 // compute y = f (x); 
 
 Object [] args = ( new Double (x) ); 
 
 Double d = (Double) f. invoke (null, args); 
 
 double y = d.doubleValue (); 
 
 } 
 

However, keep in mind that invoking a method is very slow. Only use this as a last resort, if there is no better design involving an inter face and a dynamically bound method.

Partners