1. method.invoke(Object obj, Object... args)
- java.lang.IllegalArgumentException: wrong number of arguments;
- 原理:当method的参数个数为一个时,必须将参数强转型为Object类型;但是当method的参数为多个时,必须传入等长度的多个参数或等长度的一个数组,而不能转型成Object类型;
- 易出错点:当方法有且只有一个数组类型参数的时候容易因忘转型而抛此异常
@Test
public void test_01() {
Object[] o = (Object[]) Array.newInstance(String.class, 2);
System.out.println(o.getClass());
Class clazz = TempTest.class;
try {
Method f = clazz.getMethod("f", String[].class);
/**
* 编译器会把数组当作一个可变长度参数传给对象o,而我们取得方法只有一个参数,
* 所以就会出现wrong number of arguments的异常,我们只要把字符串数组强制转换为
* 一个Object对象就可以解决这个异常了.
*/
f.invoke(new TempTest(), /*(Object)*/ o);
Method f1 = clazz.getMethod("f", String.class, String.class);
f1.invoke(new TempTest(), o);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
public void f(String[] s) {
System.out.println("f");
}
public void f(String s1, String s2) {
System.out.println("ff");
}
2. clazz.newInstance()
- java.lang.InstantiationException: [Ljava.lang.String;
- newInstance()是调用类的无参构造,出现InstantiationException异常的原因是无法实例化:
- 抽象类和接口无法构造实例、
- 没有对应构造(无参构造)的方法不能调用newInnstance()构造实例
- 数组类型没有构造方法,如果需要使用Class对象创建数组,可以使用如下方法:
- Array.newInstance(Class<?> componentType, int length)
/**
* java.lang.InstantiationException: [Ljava.lang.String;
* Caused by: java.lang.NoSuchMethodException: [Ljava.lang.String;.<init>()
*/
// @Test
public void test02 () {
String[] strings = new String[0];
Class <?> clazz = strings.getClass();
try {
clazz.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}