android 通过字符串获取或设置同名变量

public String resolveSetDataResult(String str) {
  Gson gson = new Gson();
  Map<String, DataItem> resultMap = gson.fromJson(str, new TypeToken<HashMap<String, DataItem>>() {
   }.getType());
  if (resultMap != null) {
   for (Map.Entry<String, DataItem> entry : resultMap.entrySet()) {
     DataItem it = entry.getValue();
     if (it != null) {
     try {
       Field f = this.getClass().getDeclaredField(entry.getKey());
       try {
        switch (it.type) {
        case 0:
         f.set(this, it.getField(3));

         break;
        case 1:
         f.setInt(this, Integer.parseInt(it.getField(3)));
         break;
        case 2:
         f.setFloat(this, Float.parseFloat(it.getField(3)));
        break;
       }
      } catch (IllegalAccessException e) {
        e.printStackTrace();
     }
    } catch (NoSuchFieldException e) {
     e.printStackTrace();
    }
   }
  }
  String result = gson.toJson(this, TraceLevelInfo.class);
  return result.substring(1, result.length() - 1);
 } else return null;
}

参考:https://blog.csdn.net/u011586504/article/details/80063893

猜你喜欢

转载自www.cnblogs.com/reboost/p/9699328.html
今日推荐