Java的:铸铁字符串基本类型动态(Java: Cast String to primitive t

2019-10-18 09:19发布

我想通过Java反射调用方法。

我有我的手的方法我想要调用(这样我就可以得到它的类型参数)的方法的实例,此外,我有这些参数作为字符串的值。

我有一个假设,即所有的参数都必须原语。

例如,如果我想调用下面的方法:

public static double calc(int a, double b, String op){...}

我有参数作为一个字符串数组:

String[]: {"25", "34.45", "add"}

所以,我怎么能这个字符串数组转换为包含(INT,双,字符串)数组? 我知道,我可以去了所有的基本类型,并尝试在每个类型解析值...有没有更简单的方法? 像“通用解析”的方法。

Answer 1:

你不应该去对所有的基本类型和尝试解析每个类型的值。

你应该从每一个参数的类型Method的实例,并根据参数的类型,调用合适的方法将字符串转换成所需的类型: Double.valueOf()为双( Double.TYPE ), Integer.valueOf()为一个int( Integer.TYPE )等



Answer 2:

您可以使用ConvertUtilscommons-beanutils ,参见[ convert方法( 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中))。 您需要实现的类型的数组但是在环...



Answer 3:

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.



文章来源: Java: Cast String to primitive type dynamically