前言
下面的代码用Android的SharedPreferences来解析后保存一个Bean对象,或者解析后返回一个Bean对象,这里临时记录。后续会完善
解析实例并且保存
public static void putObject(String key, Object object) { Class data = object.getClass(); //获取对象的类 Field[] fields = data.getDeclaredFields(); //获取类的声明字段数组 for (int i = 0; i < fields.length; i++) { Field f = fields[i]; f.setAccessible(true); try { String spKey = key + f.getName(); //获取字段的名称 Object value = f.get(object); //根据字段名称获取值 if (value instanceof Integer) { put(spKey, (int) value); } else if (value instanceof String) { put(spKey, (String) value); } else if (value instanceof Boolean) { put(spKey, (boolean) value); } else if (value instanceof Float) { put(spKey, (float) value); } else if (value instanceof Long) { put(spKey, (long) value); }else if (value instanceof Object){ GsonBuilder gsonb = new GsonBuilder(); Gson gson = gsonb.create(); String json = gson.toJson(value); put(spKey, json); } } catch (Exception e) { e.printStackTrace(); } } }
装载并且返回实例
public static <T> T getObject(String key, Class<T> c) { T data = null; try { data = c.newInstance(); //实例传入的类 } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } if (data == null) return data; Field[] fields = c.getDeclaredFields(); //获取声明字段数组 for (int i = 0; i < fields.length; i++) { Field f = fields[i]; f.setAccessible(true); try { String spKey = key + f.getName(); //获取字段名称 Class valueType = f.getType(); //获取字段类型 if (valueType == String.class) { //字段为String类型 f.set(data, get(spKey, "")); } else if (valueType.getSuperclass() ==Object.class){ //字段是一个Object String jsonObjext = get(spKey, ""); GsonBuilder gsonb = new GsonBuilder(); Gson gson = gsonb.create(); if (!"".equals(jsonObjext) ) { f.set(data, gson.fromJson(jsonObjext,valueType)); }else { f.set(data,null); } }else if (valueType == int.class || valueType == Integer.class) { //字段是整数类型 f.set(data, get(spKey, 0)); } else if (valueType == boolean.class || valueType == Boolean.class) { //字段是布尔值类型 f.set(data, get(spKey, false)); } else if (valueType == float.class || valueType == Float.class) { //字段是浮点类型 f.set(data, get(spKey, 0f)); } else if (valueType == long.class || valueType == Long.class) { //字段是Long类型 f.set(data, get(spKey, 0l)); } } catch (Exception e) { e.printStackTrace(); } } return data; }
本文来自博客园,作者:观心静 ,转载请注明原文链接:https://www.cnblogs.com/guanxinjing/p/12295135.html
本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。