java 动态转换类型,Java:动态地将字符串转换为基本类型

本文讨论了如何在Java中使用反射来调用方法,特别是当已知方法参数为原始类型且参数值为字符串时。建议通过获取`Method`实例的参数类型,然后针对每种原始类型调用相应的转换方法,如`Integer.valueOf()`或`Double.valueOf()`,将字符串参数转换为适当类型。
摘要由CSDN通过智能技术生成

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值