做反射的时候可能会有这种需求: 给定一个字符串和一个类型,将字符串转换为指定的类型
public class TypeUtils { public static Object stringToNullableTarget(String string, Class> t) throws Exception { return string == null ? null : t.getConstructor(String.class).newInstance(string); } public static Object stringToTarget(String string, Class> t) throws Exception { boolean nullOrEmpty = StringUtils.isEmpty(string); if (double.class.equals(t)) { return nullOrEmpty ? 0 : Double.parseDouble(string); } else if (long.class.equals(t)) { return nullOrEmpty ? 0 : Long.parseLong(string); } else if (int.class.equals(t)) { return nullOrEmpty ? 0 : Integer.parseInt(string); } else if (float.class.equals(t)) { return nullOrEmpty ? 0 : Float.parseFloat(string); } else if (short.class.equals(t)) { return nullOrEmpty ? 0 : Short.parseShort(string); } else if (boolean.class.equals(t)) { return nullOrEmpty ? 0 : Boolean.parseBoolean(string); } else if (Number.class.isAssignableFrom(t)) { return t.getConstructor(String.class).newInstance(nullOrEmpty?"0":string); } else { return nullOrEmpty ? "" : t.getConstructor(String.class).newInstance(string); } } }使用方法
public static void main(String[] args) throws Exception { System.out.println(TypeUtils.stringToTarget("0.00", BigDecimal.class)); System.out.println(TypeUtils.stringToTarget("0", int.class)); System.out.println(TypeUtils.stringToTarget("0.00", Float.class)); System.out.println(TypeUtils.stringToTarget("99999999999999999", BigInteger.class)); }
输出
0.00 0 0.0 99999999999999999
class Test{ public static void main(String[] args) throws Exception { System.out.println(TypeUtils.stringToTarget("张三", MyType.class)); } } class MyType{ String str; public MyType(String str){ this.str = str; } @Override public String toString(){ return str + "hello world!"; } }
输出
张三hello world!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)