java反射获取类的属性名和属性值

Field[] fields = contactItem.getClass().getDeclaredFields();
			for (Field field : fields) {
				Method method = null;
				Object value = null;
				String name = field.getName();
				String upperName = name.substring(0, 1).toUpperCase()
						+ name.substring(1);
				try {
					method = contactItem.getClass()
							.getMethod("get" + upperName);
					value = method.invoke(contactItem);
					if (value == null) {
						continue;
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (name.equals("tag") || name.equals("group")) {
					String valueStr = "";
					for (Map.Entry entry : ((Map<String, Map<String, String>>) value)
							.entrySet()) {
						valueStr += ((Map<String, String>) entry.getValue())
								.get("value") + ",";
					}
					if (!TextUtils.isEmpty(valueStr)) {
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("type", name);
						map.put("value",valueStr.substring(0, valueStr.length() - 1));
						leftData.add(map);
					}
				} else if(name.equals("email") || name.equals("im") || name.equals("info")){
					for (Map.Entry entry : ((Map<String, Map<String, String>>) value)
							.entrySet()) {
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("type", name);
						map.put("value",
								(Map<String, String>) entry.getValue());
						leftData.add(map);
					}
				} else if(name.equals("website") || name.equals("address") || name.equals("note")){
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("type", name);
					map.put("value", value);
					leftData.add(map);
				}
			}

你可能感兴趣的:(java反射获取类的属性名和属性值)