首先Method类代表一个方法,所以invoke(调用)就是调用Method类代表的方法。它可以让你实现动态调用,例如你可以动态的传人参数。下面是一个简单的例子。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
public class MethodTest { public static void main(String[] args) { String [] names ={ "tom" , "tim" , "allen" , "alice" }; Class<?> clazz = Test. class ; try { Method method = clazz.getMethod( "sayHi" , String. class ); for (String name:names) method.invoke(clazz.newInstance(),name); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } } } class Test { public void sayHi(String name) { System.out.println( "Hi " +name); } } |