Java如何通过原始类型作为参数的反射来调用方法
问题描述:
我在类中有以下两种方法:
I have the following two methods in a class:
public void Test(int i){
System.out.println("1");
}
public void Test(Integer i){
System.out.println("2");
}
以下代码行
this.getClass().getMethod("Test",Integer.class).invoke(this, 10);
打印 2
,如何打印 1
?
答
使用基本类型作为参数调用方法反思:
To call a method with primitive types as parameters using reflection :
您可以使用 int.class
this.getClass().getMethod("Test",int.class).invoke(this, 10);
或 Integer.TYPE
this.getClass().getMethod("Test",Integer.TYPE).invoke(this, 10);
同样适用于其他原始类型
same applies for other primitive types