First, the method class represents a way, so invoke (call) is the method that calls the methods class representative. It allows you to implement dynamic invocation, such as you can dynamically transfer the parameters. The following is a simple example.
| 123456789101112131415161718192021222324252627282930313233343536 |
publicclassMethodTest{ publicstaticvoid 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(); } }}classTest{ publicvoidsayHi(String name) { System.out.println("Hi "+name); }} |
The Invoke method function in the method class in Java reflection