Java 参数类型不匹配:简单大小写上的IllegalArgumentException
我有一个关于IllegalArgumentException的著名问题,我不知道为什么。这是我的班级:Java 参数类型不匹配:简单大小写上的IllegalArgumentException,java,reflection,illegalargumentexception,Java,Reflection,Illegalargumentexception,我有一个关于IllegalArgumentException的著名问题,我不知道为什么。这是我的班级: public class DataMapper { ... An lot of others methods that does not have the same name (because I created a method specifically for checking this exception private void hel
public class DataMapper {
... An lot of others methods that does not have the same name (because I created a method specifically for checking this exception
private void hello(String ahem) {
logger.info("Hey !");
}
}
在我的测试用例中(我尝试调用我的方法):
@测试
公开无效测试(){
Class targetClass=DataMapper.Class;
试一试{
对象t=targetClass.newInstance();
类别[]cArg=新类别[1];
cArg[0]=String.class;
Method=targetClass.getDeclaredMethod(“hello”,cArg);
方法setAccessible(true);
方法调用(t,cArg);
}捕获(无此方法例外){
logger.error(“名称不存在:”,e);
Assert.fail();
}捕获(例外e){
logger.error(“它已损坏:”,e);
Assert.fail();
}
}
它总是落在一个非法的辩论例外上。方法
对象听起来符合我的期望,但:
你知道那里发生了什么吗?
在任何复制标志之前,我已经检查了这些标志,但没有什么是完全相同的,也不起作用:
构造一个方法列表,事实上他有两个或多个同名的方法,但参数不同。
是错误的,因为他传递了字符串[]作为参数,并且编译器错误地解释了对象的完整参数列表。
是因为他忘了传论点。在这行:
method.invoke(t, cArg);
您必须将字符串作为而不是cArg
传递,后者是类的数组。类似于以下的方法将起作用:
method.invoke(t, "Test");
请包含您试图将类
引用作为参数传递给接受字符串
的方法的异常堆栈跟踪(并包含异常消息)。您需要区分“用于找到正确方法的参数类型”和“用于调用方法的参数值”。这解决了问题,谢谢Jon。我认为您必须将类传递给invoke
方法。
method.invoke(t, "Test");