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.
You can use ConvertUtils
from commons-beanutils
, see [convert
method](https://commons.apache.org/proper/commons-beanutils/javadocs/v1.9.2/apidocs/org/apache/commons/beanutils/ConvertUtils.html#convert(java.lang.String, java.lang.Class)). You need to implement the loop over the array of types however...
First your question IMHO has nothing to do with reflection. Primitive types cannot be instantiated using reflection. Reflection is for objects only.
how can I convert this String array to array that contains (int,
double, string)?
You can't. An array in Java cannot contain different data types. A workaround would be to use List<Object>
. The problem is that this will require casts later to retrieve the elements (with the possibility of getting a ClassCastException
).
Is there an easier way? something like "generic parse" method.
I don't know about anything like this in the standard library. And I doubt there's any because what should "25"
parsed to? int
? long
? float
? BigInteger
? This is up to developer, so you have to write this yourself.