一、利用反射得到Method对象,调用方法 注意要点,若调用的方法中形参为 对象数组或可变参数则会有不一样的地方
如下: 1)jdk1.4,1.5的不同
JDK1.4 method.invoke(Object obj,Object[] args); JDK1.5 method.invoke(Object obj,Object... args);2)情况一、对于方法为public void hhh(String name,String password){}
解决方案:
jdk1.4 method.invoke(obj,new String[]{"aa","bb"}); jdk1.5 method.invoke(obj,new String[]{"aa","bb"}); 或 method.invoke(obj,"aa","bb");3)情况二、对于方法为public void hhh(String... args){} 或public void hhh(String[] args){} 解决方案:
jdk1.4解决方案 method.invoke(obj,new Object[]{new String[]{"aa","bb"}}); 或 method.invoke(obj,(Object)new String[]{"aa","bb"}); jdk1.5为了兼容1.4,故也需要这样写 /* JDK1.4 method.invoke(Object obj,Object[] args); JDK1.5 method.invoke(Object obj,Object... args); 情况一,对于方法为public void hhh(String name,String password){} jdk1.4 method.invoke(obj,new String[]{"aa","bb"}); jdk1.5 method.invoke(obj,new String[]{"aa","bb"}); 或 method.invoke(obj,"aa","bb"); 情况二,对于方法为public void hhh(String... args){} 或public void hhh(String[] args){} jdk1.4解决方案 method.invoke(obj,new Object[]{new String[]{"aa","bb"}}); 或 method.invoke(obj,(Object)new String[]{"aa","bb"}); jdk1.5为了兼容1.4,故也需要这样写 */部分测试代码如下:
//public void bbb(String name,String password) 获取Method对象 @Test public void test07() throws Exception{ //加载类 Class<?> clazz = Class.forName("com.msb.test03.Person"); //获取对象 Constructor<?> constructor=clazz.getDeclaredConstructor(); constructor.setAccessible(true); Object obj = constructor.newInstance(); //public void bbb(String name,String password) 获取Method对象 Method method = clazz.getMethod("bbb",String.class,String.class); method.invoke(obj,new String[] {"aa","bb"}); //method.invoke(obj, "aa","bb");//或者这样写 } //public static void main(String[] args) 获取Method对象 @Test public void test04() throws Exception{ //加载类 Class<?> clazz = Class.forName("com.msb.test03.Person"); //获取对象 Constructor<?> constructor=clazz.getDeclaredConstructor(); constructor.setAccessible(true); Object obj = constructor.newInstance(); //public static void main(String[] args) 获取Method对象 Method method = clazz.getMethod("main",String[].class); // method.invoke(obj,(Object)new String[] {"aa","bb"}); method.invoke(obj,new Object[] {new String[] {"aa","bb"}}); } //public void aaa(Person... p) 获取Method对象 @Test public void test06() throws Exception{ //加载类 Class<?> clazz = Class.forName("com.msb.test03.Person"); //获取对象 Constructor<?> constructor=clazz.getDeclaredConstructor(); constructor.setAccessible(true); Object obj = constructor.newInstance(); //public void aaa(Person... p) 获取Method对象 Method method = clazz.getMethod("aaa",Person[].class); // method.invoke(obj,(Object)new Person[] {new Person(""),new Person("")}); method.invoke(obj,new Object[] {new Person[] {new Person(""),new Person("")}}); }