JAVA BeanUtils使用
-
通過內省(Introspector)實現,通過讀取對象屬性值來創建對象。
-
且讀取類型均可統一爲String類型,因爲屬性爲基本類型時,BeanUtils會自動幫忙轉換類型,如下代碼示例:
public class Demo3 { public static void main(String[] args) throws InvocationTargetException, IllegalAccessException { String id = "110"; String name="嘉誠"; String salary = "1000000"; Emp p = new Emp(); BeanUtils.setProperty(p,"id",id); BeanUtils.setProperty(p,"name",name); BeanUtils.setProperty(p,"salary",salary); //Emp p = new Emp(110, "fj", 30000); System.out.println(p); } }
-
如代碼塊中
Emp p = new Emp();
類中只需有默認構造函數即可,無需創建帶有參數的構造函數,屬性值通過BeanUtils.setProperty
傳入。 -
由於是基於內省實現的,所以要求所創建實例所屬類
-
若設置的屬性值爲其他的,則必須註冊一個,如下代碼示例:
String birthday = "1995-8-1"; //註冊類型轉換器 ConvertUtils.register(new Converter() { @Override public Object convert(Class type, Object value) { Date date = null; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); try { date = dateFormat.parse((String)value); } catch (ParseException e) { e.printStackTrace(); } return date; } }, Date.class);
-
上述代碼旨在將String類型的格式爲
"yyyy-MM-dd"
的屬性值轉換爲Date引用類型的屬性值。