【问题标题】:How to convert a string value to some concrete type?如何将字符串值转换为某种具体类型?
【发布时间】:2017-08-17 18:17:12
【问题描述】:

我有一个字符串值和一个具体类型的类对象。

所以我的问题是如何将字符串值转换为该类型?
看起来唯一可能的方法是做这样的事情:

private Object convertTo(String value, Class type) {
    if(type == long.class || type == Long.class)
        return Long.valueOf(value);
    if(type == int.class || type == Integer.class)
        return Integer.valueOf(value);
    if(type == boolean.class || type == Boolean.class)
        return Boolean.valueOf(value);
    ...
    return value;
}

但这看起来很丑......有没有更好的方法来做到这一点?

【问题讨论】:

  • 给我们看代码,用几行代码更容易理解
  • 我理解你想要这样的stackoverflow.com/questions/8918550/…
  • 您的意思是“转换”吗?除了它实现的接口之外,您不能将 Java 字符串 cast 到任何东西。
  • 看来我是在尝试转换,而不是强制转换。

标签: java reflection casting


【解决方案1】:

我真正想要的是某种泛型类型转换。对我最有效的是 Spring:

 org.springframework.core.convert.support.DefaultConversionService

【讨论】:

    【解决方案2】:

    根据你的描述,如果你有:

    String var = "variable";
    Class<?> type = Class.forName("your_class");// Your type
    Object o = type.cast(var);
    

    现在可能发生 3 件事:

    • o 应该是 your_class 类型
    • 如果 var 为 null,则 o 将为 null 或
    • ClassCastException 将被抛出

    【讨论】:

    • 有点,var 持有价值,可以说“123”并且类型是 Long。此代码总是抛出 ClassCastException。
    • "123" 不能转换为 Long 或 Integer 。这就是为什么我们有像atoi和itoa这样的函数。你的期望有效吗?
    【解决方案3】:
    public class Sample {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
    
            List<Class<?>> classList= new ArrayList<Class<?>>();
            classList.add(String.class);
            classList.add(Double.class);
            try {
                Class<?> myClass = Class.forName("java.lang.Double");
                //Object newInstance = myClass.newInstance();           
    
                for (Object object : classList) {               
                    if(myClass.equals(object)){
                        //do what you like here
                        System.out.println(myClass);
                    }
    
                }
    
            } catch (ClassNotFoundException e) {
    
            }
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-11
      • 1970-01-01
      • 1970-01-01
      • 2012-09-19
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 2021-11-26
      相关资源
      最近更新 更多