#眉標=.NET #副標=大內高手專欄 #大標=函數指標的進化論 #作者=文/蔡學鏞 =================================== // FncPtr.cpp #include using std::cin; using std::cout; using std::endl; // 聲明 Fnc1(), Fun2(), Twice() float Fnc1(int); float Fnc2(int); double Twice(float (*)(int), int); // 主程式 int main() { int A = 3; int B = 5; count << "Twice(Fnc1, A)的值為: " << Twice(Fnc1, A) << endl; count << "Twice(Fnc2, B)的值為: " << Twice(Fnc2, B) << endl; } float Fnc1(int N) { return float (N*N); } float Fnc2(int N) { return float (N*N*N); } double Twice(float (*pF)(int), int N) { return 2.0 * double(pF(N)); } ==================================== 執行結果: ========================================== Twice(Fnc1, A)的值為:18 Twice(Fnc2, B)的值為:250 ========================================== ========================================== import java.lang.reflect.*; class Invoke { public static void main(String[] args ) { try { Class c = Class.forName( args[0] ); Method m = c.getMethod( args[1], new Class [] { } ); Object ret = m.invoke( null, null ); System.out.println(args[0] + "." + args[1] +"() = " + ret ); } catch ( ClassNotFoundException ex ) { System.out.println("找不到此類別"); } catch (NoSuchMethodException ex ) { System.out.println("此方法不存在"); } catch (IllegalAccessException ex ) { System.out.println("沒有權限調用此方法"); } catch (InvocationTargetException ex ) { System.out.println("調用此方法時發生下列例外:\n" + ex.getTargetException() ); } } } ========================================== ========================================== java Invoke java.lang.System CurrentTimeMillis ========================================== 執行的結果如下所示: ========================================== java.lang.System.currentTimeMillis() = 1049551169474 ========================================== ========================================== class MyThread extends java.lang.Thread { public void run() { // ... } } ========================================== 再利用下面的方式來啟動此執行緒: ========================================== MyThread thread = new MyThread(); thread.start(); ========================================== ========================================== class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent evt) { // ... } } ========================================== 註冊的方式如下: ========================================== MyActionListener mal = new MyActionListener(); jButton1.addActionListener(mal); ==========================================