Java:动态地将字符串转换为基本类型 [英] Java: Cast String to primitive type dynamically

查看:667
本文介绍了Java:动态地将字符串转换为基本类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在java中通过反射来调用一个方法。



我手上有

我假设所有的参数都必须是原语。



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

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

我有一个字符串数组的参数:

  String []:{25,34.45,add} 
/ pre>

那么,我如何将这个String数组转换为包含(int,double,string)的数组?
我知道我可以遍历所有的原始类型,并尝试解析每个类型的值...有更容易的方法吗?类似通用解析方法。

解决方案

您不应该覆盖所有的原始类型并尝试解析值每种类型。



您应该从 Method 实例获取每个参数的类型,并根据参数的类型,调用适当的方法将String转换为所需类型: Double.valueOf()为double( Double.TYPE ), Integer.valueOf()用于int( Integer.TYPE )等。


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.

这篇关于Java:动态地将字符串转换为基本类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆