gpt4 book ai didi

java - 字符串到对象的转换,

转载 作者:行者123 更新时间:2023-12-02 02:44:45 24 4
gpt4 key购买 nike

有时我会遇到需要将 String 值转换为对象的情况。通常我最终会得到一个自定义方法。

这是一个示例:

@Nullable
public static Object valueOf(Class pParamType, String pValue)
{
if (pValue == null) return null;
if ("null".equals(pValue)) return null;

if (String.class.equals(pParamType)) return pValue;
if (Number.class.equals(pParamType)) return Double.valueOf(pValue);
if (Long.class.equals(pParamType) || Long.TYPE.equals(pParamType)) return Long.valueOf(pValue);
if (Double.class.equals(pParamType) || Double.TYPE.equals(pParamType)) return Double.valueOf(pValue);
if (Integer.class.equals(pParamType) || Integer.TYPE.equals(pParamType)) return Integer.valueOf(pValue);
if (Byte.class.equals(pParamType) || Byte.TYPE.equals(pParamType)) return Byte.valueOf(pValue);
if (Short.class.equals(pParamType) || Short.TYPE.equals(pParamType)) return Short.valueOf(pValue);
if (Float.class.equals(pParamType) || Float.TYPE.equals(pParamType)) return Float.valueOf(pValue);

if (Date.class.equals(pParamType))
{
try
{
return Formatter.parse(pValue, DATE_PATTERN);
}
catch (Exception e)
{
throw new IllegalArgumentException("Illegal date format");
}
}

if (Boolean.class.equals(pParamType) || Boolean.TYPE.equals(pParamType))
{
return Boolean.valueOf(pValue);
}

throw new IllegalArgumentException("Parameters of type [" + pParamType.getName() + "] are not supported");
}

我确实意识到不可能转换为任何对象。但大多数 java.lang 类确实有一个 valueOf 方法

但我讨厌重复自己,而且我感觉应该已经有一些东西可以做同样的事情,甚至可能涵盖更多内容。

我的问题是:

jdk在java框架中提供类似的实用程序类或方法吗?或者其他框架提供什么? (例如 apache commons、spring、guava...)

最佳答案

使用反射,您可以尝试找到带有 String 参数的构造函数并调用构造函数

public static void main(String[] args) throws Exception{
System.out.println(valueOf(String.class, ""));
System.out.println(valueOf(Long.class, "1"));
System.out.println(valueOf(Integer.class, "1"));
System.out.println(valueOf(Byte.class, "1"));
System.out.println(valueOf(Short.class, "1"));
System.out.println(valueOf(Double.class, "1.1"));
System.out.println(valueOf(Float.class, "1.1"));
System.out.println(valueOf(Boolean.class, "true"));
}

public static Object valueOf(Class pParamType, String pValue) throws Exception
{

if (pValue == null) return null;
if ("null".equals(pValue)) return null;

Constructor constructor = pParamType.getConstructor(String.class);
if (constructor!=null) {
return constructor.newInstance(pValue);
}
//... keep the logic for Date
throw new IllegalArgumentException("Parameters of type [" + pParamType.getName() + "] are not supported");
}

关于java - 字符串到对象的转换,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44798356/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com