Pra*_*een 1 java reflection casting
我在java中使用反射.
我开始知道我在运行时传递的方法参数的类型.所以我将文件中的参数值提取到字符串变量中.
现在,如果我知道参数类型为整数,如果我传递一个包含我得到的字符串值的对象
参数类型不匹配java.lang.IllegalArgumentException:参数类型不匹配
Class classDefinition = Class.forName("webservices."+objectName);
String methodName = set"+fieldNameAttay[i].substring(0,1)).toUpperCase()+fieldNameAttay[i].substring(1); Field f = classDefinition.getDeclaredField(fieldNameAttay[i]);
try
{
//argType = f.getType();
Method meth = classDefinition.getMethod(methodName,f.getType());
Object arg = new Object[]{fieldValueArray[i]}; //fieldValueArray[i] is always string array
meth.invoke(object, arg); //If f.getType is Integer this //throws ex
}
catch (Exception e)
{
System.err.println(e.getMessage());
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
你不能将字符串转换为整数 - 你可以解析它.例如:
if (parameterType == int.class && argumentType == String.class)
{
int integerArgument = Integer.parseInt((String) argumentValue);
// Now call the method appropriately
}
Run Code Online (Sandbox Code Playgroud)
当然,你还需要考虑Integer以及int.
| 归档时间: |
|
| 查看次数: |
2837 次 |
| 最近记录: |