public void castType(String str,String type){
str 是 已知的字符串,
type 是 查出来的需要转的类型,(如 integer或float不定)
但确定str 就是 要转的 type 类型
方法返回类型type的str的值
}
str 是 已知的字符串,
type 是 查出来的需要转的类型,(如 integer或float不定)
但确定str 就是 要转的 type 类型
方法返回类型type的str的值
}
if("Integer".equals(type)){
return Integer.valueOf(str);
}else if("Float".equals(type)){
return Float.valueOf(str);
}
return null;
}
public float castType("19.9",float){
retrun ;
}
public String castType("fdada",String){
retrun ;
}
LZ是这个意思吗?
public static void main(String[] args){
System.out.println(cast("123", Integer.class));
System.out.println(cast("123.123", Double.class));
} public static <T extends Number> T cast(String s, Class<T> t){
try{
return (T) t.getDeclaredMethod("valueOf", String.class).invoke(null, s);
}catch(Exception e){
throw new RuntimeException(e);
}
}
}
public static Object castType(String str,String type) throws Exception {
Class obj = Class.forName("java.lang."+type);
Method m = obj.getDeclaredMethod("valueOf",String.class);
return m.invoke(null,str) ;
}
public static void main(String[] args) throws Exception {
String str = "12";
System.out.println(castType(str,"Integer"));
System.out.println(castType(str,"Float"));
}