com.garmin.util.ObjectUtils Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of garmin-oauth Show documentation
Show all versions of garmin-oauth Show documentation
Package garmin license, new user license to app
The newest version!
package com.garmin.util;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class ObjectUtils {
// public static void main(String[] args) {
// UserInfo userInfo =new UserInfo();
// userInfo.setUserId("111");
// userInfo.setSid("a");
// userInfo.setUserAccessToken("1213123");
// userInfo.setUserAccessSecret("13123");
//// T t = new T();
//// t.setS("11");
// System.out.println(mapToString(userInfo,true));
// }
public static String mapToString(Map map){
StringBuilder stringBuilder =new StringBuilder();
return getString(map, stringBuilder);
}
private static String getString(Map map, StringBuilder stringBuilder) {
if(map==null || map.isEmpty()){
return null;
}
stringBuilder.append("?");
int i=0;
for(String key:map.keySet()){
stringBuilder.append(key).append("=").append(map.get(key));
i++;
if(i!=map.size()){
stringBuilder.append("&");
}
}
return stringBuilder.toString();
}
public static String mapToString(Object obj,boolean isDecode){
StringBuilder stringBuilder =new StringBuilder();
Map map=converMap(obj,isDecode);
return getString(map, stringBuilder);
}
public static Map converMap(Object obj) {
return converMap(obj,false);
}
public static Map converMap(Object obj,boolean isDecode) {
Map map = new HashMap<>();
if(obj==null){
return null;
}
Field[] fields = obj.getClass().getDeclaredFields();//获取类的各个属性值
for(Field field : fields){
String fieldName = field.getName();//获取类的属性名称
if(getValueByFieldName(fieldName,obj)!=null) {//获取类的属性名称对应的值
Object value = getValueByFieldName(fieldName, obj);
if(isDecode){
try {
value=URLEncoder.encode(value+"","UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
map.put(fieldName,value );
}else{
map.put(fieldName,value);
}
}
}
return map;
}
/**
* 根据属性名获取该类此属性的值
* @param fieldName
* @param object
* @return
*/
public static Object getValueByFieldName(String fieldName,Object object){
String firstLetter=fieldName.substring(0,1).toUpperCase();
String getter = "get"+firstLetter+fieldName.substring(1);
try {
Method method = object.getClass().getMethod(getter);
return method.invoke(object);
} catch (Exception e) {
return null;
}
}
}