タケチ 的个人资料人が存在するってどういうこと?照片日志列表 工具 帮助
2月5日

メソッドの呼び出し

2008年2月5日(火) ハレハレ
 
newを使わずにインスタンスを生成できたので、今度はMethodクラスを使ってメソッドを呼び出すことにチャレンジです。

========================================================
  String className = "TestHashTable";
  try{
   Class nodeClass = Class.forName(className);
   try{
   
    Method nodeMethod = nodeClass.getMethod("methodA", new Class[]{});
    System.out.println("method call invoke():" +  nodeMethod.invoke(nodeClass.newInstance(), new Object[]{}));
   
    Method nodeMethodB = nodeClass.getMethod("methodB", new Class[]{int.class});
    System.out.println("method call invoke():" +  nodeMethodB.invoke(nodeClass.newInstance(), new Object[]{new Integer(100)}));
   
    Method nodeMethodC = nodeClass.getMethod("methodC", new Class[]{String.class, int.class});
    System.out.println("method call invoke():" +  nodeMethodC.invoke(nodeClass.newInstance(), new Object[]{"moji", 20}));
   
   }catch(NoSuchMethodException e){
    e.printStackTrace();
   }catch(IllegalAccessException e){
    e.printStackTrace();
   }catch(InvocationTargetException e){
    e.printStackTrace();
   }catch(InstantiationException e){
    e.printStackTrace();
   }
  }catch(ClassNotFoundException e){
   System.out.println("vrml97 Loader: Initialization error: Can't " + "find class for VRML node: " + className);
   e.printStackTrace();
  }

========================================================

メソッドの戻り値は元のメソッドの戻り値同じで
戻り値がprimitive型の場合はラッパークラスとして返り、
voidの場合は、nullが返る。

▲呼び出すメソッドに引数なし
nodeClass.getMethod("methodA")
nodeClass.getMethod("methodA", new Class[]{})
nodeClass.getMethod("methodA", new Class[0])
getMethodでクラスから取得する
第1引数:取得するメソッド名
第2引数:メソッド引数の型を指定する

nodeMethod.invoke(nodeClass.newInstance())
nodeMethod.invoke(nodeClass.newInstance(), new Object[]{})
nodeMethod.invoke(nodeClass.newInstance(), new Object[0])
invokeでメソッドを呼び出す
第1引数:メソッドが属するクラスのインスタンス
第2引数:呼び出すメソッドに渡す値

▲呼び出すメソッドに引数あり
nodeClass.getMethod("methodB", new Class[]{int.class})
nodeMethodB.invoke(nodeClass.newInstance(), new Object[]{1})

nodeClass.getMethod("methodC", new Class[]{String.class, int.class})
nodeMethodC.invoke(nodeClass.newInstance(), new Object[]{"moji", 1})