how to cast string to integer at runtime
I am using reflection in java.
I am getting to know the type of method parameter I am passing at run time. So I am fetching the parameter value from file into a string variable.
SO now if i get to know that the parameter type as integer and if i pass an object containting the string value I am getting
argument type mismatch java.lang.IllegalArgumentException: argument type mismatch
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();
}
You can't cast a string to an integer - you can parse it though. For example:
if (parameterType == int.class && argumentType == String.class)
{
int integerArgument = Integer.parseInt((String) argumentValue);
// Now call the method appropriately
}
Of course, you also need to consider Integer
as well as int
.
How about
Integer.parseInt((String) stringObj)
Note that casting can happen only if the two objects belong in the same hierarchy. So this is not casting.
If the only types you are using are String and Integer, checking the type and then using Integer.parseInt
might be the simplest thing to do.
However if you have more different types, I would suggest checking out the good old JavaBeans framwork: http://download.oracle.com/javase/tutorial/javabeans/index.html
And especially the PropertyEditors http://download.oracle.com/javase/7/docs/api/java/beans/PropertyEditor.html http://download.oracle.com/javase/7/docs/api/java/beans/PropertyEditorManager.html
The PropertyEditors allow you to set the value as text, and then retrieve the value as correct type. Assuming you have implemented and registered the property editors, the steps to get the correct type are similer to this:
- Find out the type of the parameter
- Retrieve a PropertyEditor for that type
- Use setAsText and getValue in the property editor to convert the value to correct type
...or You can just adapt the same mechanism to your simple needs by implementing your own conversion framework with similar but simpler interfaces.
System.out.println(Integer.parseInt(obj.toString()))
There's another way to do it:
Integer number = Integer.valueOf("1");
精彩评论