你的方法可以有一個單一的代碼行:
public static <T> T parseObjectFromString(String s, Class<T> clazz) throws Exception {
return clazz.getConstructor(new Class[] {String.class }).newInstance(s);
}
測試不同類:
Object obj1 = parseObjectFromString("123", Integer.class);
System.out.println("Obj: " + obj1.toString() + "; type: " + obj1.getClass().getSimpleName());
BigDecimal obj2 = parseObjectFromString("123", BigDecimal.class);
System.out.println("Obj: " + obj2.toString() + "; type: " + obj2.getClass().getSimpleName());
Object obj3 = parseObjectFromString("str", String.class);
System.out.println("Obj: " + obj3.toString() + "; type: " + obj3.getClass().getSimpleName());
Object obj4 = parseObjectFromString("yyyy", SimpleDateFormat.class);
System.out.println("Obj: " + obj4.toString() + "; type: " + obj4.getClass().getSimpleName());
輸出:
Obj: 123; type: Integer
Obj: str; type: String
Obj: 123; type: BigDecimal
Obj: [email protected]; type: SimpleDateFormat
請添加您想要使用該方法的上下文。這將有助於提供適當的解決方案。 – helios 2010-01-19 11:24:52