1、web開發中,對於頁面提交的屬性封裝到對象屬性中著實是件麻煩事,自己寫多了也想偷點懶,參照網上其他的一些文章,封裝了一個簡單的方法,貼上代碼
[java]
- /**
- * 對象快速封裝的方法
- *
- * @param object 需要進行屬性封裝的對象
- * @param fields 需要進行封裝的屬性
- * @param params 需要進行設置的值
- */
- public static void encapsulateObject(Object object, String[] fields,
- Object[] params) {
- Class<?> cl = object.getClass();
- for (int i = 0; i < fields.length; i++) {
- StringBuffer buffer = new StringBuffer();
- try {
- Field field = cl.getDeclaredField(fields[i]);
- // 得到參數類型
- Class<?> paramType = field.getType();
- buffer.append("set");
- buffer.append(fields[i].substring(0, 1).toUpperCase());
- buffer.append(fields[i].substring(1));
- Method method = cl.getDeclaredMethod(buffer.toString(),
- paramType);
- method.invoke(object, params[i]);
- } catch (SecurityException e) {
- e.printStackTrace();
- } catch (NoSuchFieldException e) {
- e.printStackTrace();
- } catch (NoSuchMethodException e) {
- e.printStackTrace();
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- e.printStackTrace();
- }
- }
-
- }
使用一下:
[java]
- public static void main(String[] args) {
- Admin admin = new Admin();
- String[] method = { "userName", "realName", "lastLoginTime" };
- Object[] param = { "dfd", "zhangsan",
- new Timestamp(new Date().getTime()) };
- encapsulateObject(admin, method, param);
- System.out.println(admin);
- }
復寫toString(),看一下結果:
[java]
- Admin [userName=dfd, realName=zhangsan, password=null, unit=null, lastLoginTime=2011-10-11 13:15:05.593, isdel=0, roles=[]]