I want to invoke a method by reflection in java.
I have on my hand the Method instance of the method I want to invoke (so I can get the types of its parameters), in addition, I have the values of these parameters as Strings.
I have an assumption that all the parameters MUST be primitives.
for example, if I want to invoke the following method:
public static double calc(int a, double b, String op){...}
I have the parameter as a String Array:
String[]: {"25", "34.45", "add"}
So, how can I convert this String array to array that contains (int, double, string)?
I know that I can go over all the primitive types and try to parse the value in each type... Is there an easier way? something like "generic parse" method.
解决方案
You shouldn't go over all the primitive types and try to parse the value in each type.
You should get the type of each argument from the Method instance, and based on the type of the argument, call the appropriate method to transform the String into the required type: Double.valueOf() for a double (Double.TYPE), Integer.valueOf() for an int (Integer.TYPE), etc.