java中的反射,invoke方法详解是什么?
就是调用类中的方法,最简单的用法是可以把方法参数化,invoke(class, method)比如你Test类里有一系列名字相似的方法setValue1、setValue2等等。可以把方法名存进数组v[],然后循环里invoke(test,v[i]),就顺序调用了全部setValue
如:public class MyTest{ 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 (IllegalAccessExcepti e.printStackTrace( } catch (IllegalArgumentException {e.printStackTrace();} catch (InvocationTargetException e)e.printStackTrace(); } catch (InstantiationException e {e.printStackTrace( }class Test{public void sayHi(String name){ System.out.println("Hi "+name); }