package com.bnl.core.util;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* java オブジェクトがMapのキー・バリュー形式に変換される
*
*
**/
public class ObjectToMap {
/**
* マップにクラス・クエリ・メソッドを追加(属性の値がint型の場合、0になると追加されない),
* String型またはLong型の場合、属性値はNULLである。”(アクセシオンなし)
*注:変換されるオブジェクトはオブジェクトでなければならない。
*/
public static Map<String, Object> setConditionMap(Object obj){
Map<String, Object> 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)//クラスの属性名に対応する値を取得する
map.put(fieldName, getValueByFieldName(fieldName,obj));
}
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, new Class[]{});
Object value = method.invoke(object, new Object[] {});
return value;
} catch (Exception e) {
return null;
}
}
}