03.05 Java操作bean、屬性、方法的使用工具類

在實際的項目開發中,反射操作類的實例、屬性賦值、執行方法是常規的操作,雖然spring提供了比較完整的API來執行上述操作,不過在實際的應用中,spring的函數隱藏比較深,比較分散,小夥伴們可能懶得花時間去尋找。本類集成了一些常規操作,值得收藏,請關注展翅,展翅會定時更新有項目實戰價值的代碼和技術。

<code>
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.util.ObjectUtils;

import com.esotericsoftware.reflectasm.MethodAccess;
import com.ivt.monitor.utils.common.CommonUtils;
import com.ivt.monitor.utils.common.StringUtil;

public class ReflectASMUtils {
\t/**
\t * Class,MethodAccess的緩存map
\t */
\tprivate static Map<class>, MethodAccess> classMethodAccessMap;
\tstatic{
\t\tclassMethodAccessMap = new HashMap<class>, MethodAccess>();
\t}
\t
\t/**
\t * 根據字段名獲取對應的bean的值

\t * 為了避免因為bean的set,get不規範而出異常,加上PropertyUtils.getProperty(bean, field);
\t * @param bean
\t * @param field
\t * @return
\t * @throws NoSuchMethodException
\t * @throws InvocationTargetException
\t * @throws IllegalAccessException
\t */
\tpublic static Object getProperty(Object bean, String field) throws IllegalAccessException,
\tInvocationTargetException, NoSuchMethodException{\t\t
\t\ttry{\t\t
\t\t\tClass> clazz = bean.getClass(); \t\t\t

\t\t\tString methodName = "get".concat(field.substring(0, 1).toUpperCase()
\t\t\t\t\t.concat(field.substring(1, field.length())));\t\t\t
\t\t\tMethodAccess access = getCacheMethodAccess(clazz);
\t\t\tObject obj = access.invoke(bean, methodName);\t\t\t
\t\t\t/*if(obj != null && obj instanceof Date){
\t\t\t\t
\t\t\t\tobj = CommonUtils.getDateString((Date) obj);
\t\t\t}*/
\t\t\t
\t\t\treturn obj;
\t\t\t
\t\t}catch (Exception e) {\t\t
\t\t\treturn PropertyUtils.getProperty(bean, field);
\t\t}
\t}
\t
\t/**
\t * 根據字段名為bean設置對應的值

\t * 為了避免因為bean的set,get不規範而出異常,加上PropertyUtils.setProperty(bean, field, value);
\t * @param bean
\t * @param field
\t * @param value
\t * @throws NoSuchMethodException
\t * @throws InvocationTargetException
\t * @throws IllegalAccessException
\t */
\tpublic static void setProperty(Object bean, String field, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException{
\t\t
\t\ttry{
\t\t\t
\t\t\tClass> clazz = bean.getClass();
\t\t\t
\t\t\tString methodName = "set".concat(field.substring(0, 1).toUpperCase().concat(field.substring(1, field.length())));
\t\t\t
\t\t\tMethodAccess access = getCacheMethodAccess(clazz);
\t\t\taccess.invoke(bean, methodName, value);
\t\t}catch (Exception e) {
\t\t\t
\t\t\tPropertyUtils.setProperty(bean, field, value);
\t\t}
\t}
\t
\t////////////
\t
\t/**
\t * map返回成一個bean

\t * @param clazz
\t * @param map
\t * @return
\t */
\tpublic static T setBeanValue(Class clazz, Map<string> map){\t\t
\t\ttry{\t\t\t
\t\t\tT bean = clazz.newInstance();\t\t\t
\t\t\tif(bean == null || CommonUtils.isCollectionEmpty(map)){\t\t\t\t
\t\t\t\treturn null;
\t\t\t}\t\t\t
\t\t\tSet<string> keys = map.keySet();
\t\t\tfor(String field : keys){\t\t\t\t
\t\t\t\tString methodName = "set".concat(field.substring(0, 1).toUpperCase().
\t\t\t\t\t\tconcat(field.substring(1, field.length())));\t\t\t\t
\t\t\t\tMethodAccess access = getCacheMethodAccess(clazz);
\t\t\t\taccess.invoke(bean, methodName, map.get(field));\t\t\t\t
\t\t\t}\t\t\t
\t\t\treturn bean;\t\t\t
\t\t}catch(Exception e){\t\t\t
\t\t\treturn null;
\t\t}
\t\t
\t}
\t
\t/**
\t * mapList返回成一個bean list
\t * @param clazz
\t * @param mapList
\t * @return
\t */
\tpublic static List setBeanListValue(Class clazz, List> mapList){
\t\t
\t\tif(clazz == null || CommonUtils.isCollectionEmpty(mapList)){
\t\t\t
\t\t\treturn null;
\t\t}
\t\t
\t\tList list = new ArrayList();
\t\t
\t\tfor(Map<string> map : mapList){
\t\t\t
\t\t\tlist.add(setBeanValue(clazz, map));

\t\t}
\t\t
\t\treturn list;
\t}
\t
\t////////////
\t
\t/**
\t * 獲取bean所有字段的json
\t * @param bean
\t * @return
\t */
\tpublic static JSONObject getBeanJSONObjectByField(Object bean){
\t\t
\t\tJSONObject json = new JSONObject();
\t\t
\t\tList<string> fieldList = getFieldNameList(bean);
\t\t
\t\tif(CommonUtils.isCollectionEmpty(fieldList)){
\t\t\treturn json;
\t\t}
\t\t
\t\tObject obj = null;
\t\tfor(String field : fieldList){
\t\t\t
\t\t\ttry {
\t\t\t\tobj = getProperty(bean, field);
\t\t\t} catch (Exception e) {
\t\t\t}
\t\t\t
\t\t\tjson.put(field, obj);
\t\t\t
\t\t}
\t\t
\t\treturn json;
\t}
\t
\t/**
\t * app獲取bean所有字段的json
\t * @param bean
\t * @return
\t */
\tpublic static JSONObject getBeanJSONObjectByFieldForApp(Object bean){
\t\t
\t\t/*Gson gson = new GsonBuilder().serializeNulls().create();

\t\tString gsonString = gson.toJson(bean);
\t\t
\t\treturn JSONObject.fromObject(gsonString);*/

\t\t
\t\tJSONObject json = new JSONObject();
\t\t
\t\tList<string> fieldList = getFieldNameList(bean);
\t\t
\t\tif(CommonUtils.isCollectionEmpty(fieldList)){
\t\t\treturn json;
\t\t}
\t\t
\t\tObject obj = null;
\t\tfor(String field : fieldList){
\t\t\t
\t\t\ttry {
\t\t\t\tobj = getPropertyForApp(bean, field);
\t\t\t} catch (Exception e) {
\t\t\t}
\t\t\t
\t\t\tjson.put(field, obj);
\t\t\t
\t\t}
\t\t
\t\treturn json;
\t}
\t
\t/**
\t * 根據JsonConfig,獲取bean指定字段的json
\t * @param bean
\t * @param config
\t * @param fields
\t * @return
\t */
\tpublic static JSONObject getBeanJSONObjectByField(Object bean, JsonConfig config, String ... fields){
\t\t
\t\tJSONObject json = JSONObject.fromObject(bean, config);
\t\t
\t\tif(CommonUtils.isCollectionEmpty(fields)){
\t\t\treturn json;
\t\t}
\t\t
\t\tJSONObject retJson = new JSONObject();
\t\tObject obj = null;
\t\t
\t\tfor(String field : fields){
\t\t\t
\t\t\tobj = json.get(field);
\t\t\t
\t\t\tretJson.put(field, obj);
\t\t}
\t\t
\t\treturn retJson;

\t}
\t
\t/**
\t * 獲取bean指定字段的json
\t * @param bean
\t * @param fields
\t * @return
\t */
\tpublic static JSONObject getBeanJSONObjectByField(Object bean, String ... fields){\t\t
\t\tJSONObject json = new JSONObject();\t\t
\t\tif(CommonUtils.isCollectionEmpty(fields)){
\t\t\treturn json;
\t\t}\t\t
\t\tObject obj = null;
\t\tfor(String field : fields){\t\t\t
\t\t\ttry {
\t\t\t\tobj = getProperty(bean, field);
\t\t\t} catch (Exception e) {
\t\t\t} \t\t\t
\t\t\tjson.put(field, obj);
\t\t}\t\t
\t\treturn json;
\t}
\t
\t/**
\t * 獲取bean所有的get方法的json,key為對應的生成的字段
\t * @param bean
\t * @return
\t */
\tpublic static JSONObject getBeanJSONObjectByMethod(Object bean){
\t\t
\t\tJSONObject json = new JSONObject();
\t\t
\t\tList<string> getMethodList = getGetMethodNameList(bean);
\t\t
\t\tif(CommonUtils.isCollectionEmpty(getMethodList)){
\t\t\treturn json;
\t\t}
\t\t
\t\tClass> clazz = bean.getClass();
\t\t
\t\tString key = "";
\t\tString value = "";
\t\t
\t\tMethodAccess access = null;
\t\tObject obj = null;
\t\t
\t\tfor(String methodName : getMethodList){

\t\t\t
\t\t\tkey = methodName.substring(3, 4).toLowerCase().concat(methodName.substring(4, methodName.length()));
\t\t\t
\t\t\tif(StringUtil.isStrEmpty(key)){
\t\t\t\tcontinue;
\t\t\t}
\t\t\t
\t\t\taccess = getCacheMethodAccess(clazz);
\t\t\tobj = access.invoke(bean, methodName);
\t\t\t
\t\t\tif(obj != null && obj instanceof Date){
\t\t\t\t
\t\t\t\tvalue = StringUtil.getDateString((Date) obj); //除了日期,其他都利用spring的幫助類
\t\t\t}else{
\t\t\t\t
\t\t\t\tvalue = ObjectUtils.getDisplayString(obj); //利用spring的幫助類
\t\t\t}
\t\t\t
\t\t\tjson.put(key, value);
\t\t\t
\t\t}
\t\t
\t\treturn json;
\t}
\t
\t/**
\t * 給JSONObject對應的值增加前綴
\t * @param json
\t * @param map
\t * @return
\t */
\tpublic static JSONObject setUpPrefix(JSONObject json, Map<string> map){
\t\t
\t\tif(CommonUtils.isCollectionEmpty(map)){
\t\t\t
\t\t\treturn json;
\t\t}
\t\t
\t\tSet<string> keys = map.keySet();
\t\t
\t\tObject value = null;
\t\tfor(String key : keys){
\t\t\t
\t\t\tvalue = json.get(key);
\t\t\tif(value != null && !"".equals(value.toString())){
\t\t\t\t
\t\t\t\tjson.put(key, map.get(key) + value);
\t\t\t}

\t\t}
\t\t
\t\treturn json;
\t}
\t
\t//////////////
\t
\t/**
\t * 根據JsonConfig,獲取bean list指定字段的JSONArray
\t * @param beanList
\t * @param config
\t * @param fields
\t * @return
\t */
\tpublic static JSONArray getBeanListJSONArrayByField(List> beanList, JsonConfig config, String ... fields){
\t\t
\t\tJSONArray array = new JSONArray();
\t\t
\t\tif(CommonUtils.isCollectionEmpty(beanList) || CommonUtils.isCollectionEmpty(fields)){
\t\t\t
\t\t\treturn array;
\t\t}
\t\t
\t\tfor(Object bean : beanList){
\t\t\t
\t\t\tarray.add(getBeanJSONObjectByField(bean, config, fields));
\t\t}
\t\t
\t\treturn array;
\t}
\t
\t
\t/**
\t * 獲取bean list 的JSON數組
\t * @param beanList
\t * @param fields
\t * @return
\t */
\tpublic static JSONArray getBeanListJSONArray(List> beanList){\t\t
\t\tJSONArray array = new JSONArray();\t\t
\t\tif(CommonUtils.isCollectionEmpty(beanList)){\t\t\t
\t\t\treturn array;
\t\t}\t\t
\t\tfor(Object bean : beanList){\t\t\t
\t\t\tarray.add(JSONObject.fromObject(bean));
\t\t}\t\t
\t\treturn array;
\t}
\t

\t/**
\t * 獲取bean list指定字段的JSONArray
\t * @param beanList
\t * @param fields
\t * @return
\t */
\tpublic static JSONArray getBeanListJSONArrayByField(List> beanList, String ... fields){\t\t
\t\tJSONArray array = new JSONArray();\t\t
\t\tif(CommonUtils.isCollectionEmpty(beanList) || CommonUtils.isCollectionEmpty(fields)){\t\t\t
\t\t\treturn array;
\t\t}\t\t
\t\tfor(Object bean : beanList){\t\t\t
\t\t\tarray.add(getBeanJSONObjectByField(bean, fields));
\t\t}\t\t
\t\treturn array;
\t}
\t
\t/**
\t * app獲取bean list指定字段的JSONArray
\t * @param beanList
\t * @param fields
\t * @return
\t */
\tpublic static JSONArray getBeanListJSONArrayByFieldForApp(List> beanList, String ... fields){
\t\t
\t\tJSONArray array = new JSONArray();
\t\t
\t\tif(CommonUtils.isCollectionEmpty(beanList) || CommonUtils.isCollectionEmpty(fields)){
\t\t\t
\t\t\treturn array;
\t\t}
\t\t
\t\tfor(Object bean : beanList){
\t\t\t
\t\t\tarray.add(getBeanJSONObjectByFieldForApp(bean, fields));
\t\t}
\t\t
\t\treturn array;
\t}
\t
\t/**
\t * 獲取bean list所有的get方法的JSONArray
\t * @param beanList
\t * @return
\t */
\tpublic static JSONArray getBeanListJSONArrayByMethod(List> beanList){
\t\t
\t\tJSONArray array = new JSONArray();

\t\t
\t\tif(CommonUtils.isCollectionEmpty(beanList)){
\t\t\t
\t\t\treturn array;
\t\t}
\t\t
\t\tfor(Object bean : beanList){
\t\t\t
\t\t\tarray.add(getBeanJSONObjectByField(bean));
\t\t}
\t\t
\t\treturn array;
\t}
\t
\t/**
\t * 給JSONArray對應的值增加前綴
\t * @param array
\t * @param map
\t * @return
\t */
\tpublic static JSONArray setUpPrefix(JSONArray array, Map<string> map){
\t\t
\t\tif(CommonUtils.isCollectionEmpty(map)){
\t\t\t
\t\t\treturn array;
\t\t}
\t\t
\t\tint size = array.size();
\t\tif(size <= 0){
\t\t\t
\t\t\treturn array;
\t\t}
\t\t
\t\tJSONObject json = null;
\t\t
\t\tfor(int i=0; i<size>\t\t\t
\t\t\tjson = setUpPrefix(array.getJSONObject(i), map);
\t\t\tarray.set(i, json);
\t\t}
\t\t
\t\treturn array;
\t}
\t
\t////
\t
\t/**
\t * 獲取所有的字段
\t * @param bean
\t * @return

\t */
\tprivate static List<string> getFieldNameList(Object bean){
\t\t
\t\tClass> clazz = bean.getClass();
\t\tField[] implFs = clazz.getDeclaredFields(); //實現類,也就是本身的字段
\t\t
\t\tList<string> fieldNameList = new ArrayList<string>();
\t\t
\t\tString name = "";
\t\t
\t\tfor(Field fs : implFs){
\t\t\t
\t\t\tname = fs.getName();
\t\t\t
\t\t\tif(("serialVersionUID").equalsIgnoreCase(name))
\t\t\t\tcontinue;
\t\t\t
\t\t\tfieldNameList.add(name);
\t\t}
\t\t
\t\treturn fieldNameList;
\t}
\t
\t/**
\t * 獲取所有的方法
\t * @param name
\t * @return
\t */
\tprivate static List<string> getGetMethodNameList(Object bean){
\t\t
\t\tList<string> getMethodList = new ArrayList<string>();
\t\t
\t\tClass> clazz = bean.getClass();
\t\t
\t\tMethod[] mds = clazz.getMethods();
\t\tString name = null;
\t\t
\t\tfor(Method md : mds){
\t\t\t
\t\t\tname = md.getName();
\t\t\t
\t\t\tif(name.startsWith("get") && !"getClass".equalsIgnoreCase(name)){
\t\t\t\t
\t\t\t\tgetMethodList.add(name);
\t\t\t}
\t\t\t
\t\t}
\t\t
\t\treturn getMethodList;

\t}
\t
\t/**
\t * 因為MethodAccess.get(clazz);比較耗時,所以緩存起來
\t * @param clazz
\t * @return
\t */
\tprivate static MethodAccess getCacheMethodAccess(Class> clazz){
\t\t
\t\tMethodAccess obj = classMethodAccessMap.get(clazz);
\t\tif(obj == null){
\t\t\t
\t\t\tMethodAccess access = MethodAccess.get(clazz);
\t\t\tclassMethodAccessMap.put(clazz, access);
\t\t\t
\t\t\treturn access;
\t\t}
\t\t
\t\treturn obj;
\t}
\t
\t/**
\t * 獲取bean指定字段的json
\t * @param bean
\t * @param fields
\t * @return
\t */
\tpublic static JSONObject getBeanJSONObjectByFieldForApp(Object bean, String ... fields){
\t\t
\t\tJSONObject json = new JSONObject();
\t\t
\t\tif(CommonUtils.isCollectionEmpty(fields)){
\t\t\treturn json;
\t\t}
\t\t
\t\tObject obj = null;
\t\tfor(String field : fields){
\t\t\t
\t\t\ttry {
\t\t\t\tobj = getPropertyForApp(bean, field);
\t\t\t} catch (Exception e) {
\t\t\t}
\t\t\t
\t\t\tjson.put(field, obj);
\t\t}
\t\t
\t\treturn json;
\t}
\t

\t/**
\t * app的日期返回long
\t * @param bean
\t * @param field
\t * @return
\t * @throws IllegalAccessException
\t * @throws InvocationTargetException
\t * @throws NoSuchMethodException
\t */
\tprivate static Object getPropertyForApp(Object bean, String field) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException{
\t\t
\t\ttry{
\t\t
\t\t\tClass> clazz = bean.getClass();
\t\t\t
\t\t\tString methodName = "get".concat(field.substring(0, 1).toUpperCase().concat(field.substring(1, field.length())));
\t\t\t
\t\t\tMethodAccess access = getCacheMethodAccess(clazz);
\t\t\tObject obj = access.invoke(bean, methodName);
\t\t\t
\t\t\tif(obj != null && obj instanceof java.util.Date){
\t\t\t\t
\t\t\t\tobj = new Long(((Date) obj).getTime());
\t\t\t}
\t\t\t
\t\t\tif(obj == null){
\t\t\t\t
\t\t\t\t//獲取字段的類型
\t\t\t\tField _field = clazz.getDeclaredField(field);
\t\t\t Class> fieldType = _field.getType();
\t\t\t
\t\t\t if(fieldType == Number.class || fieldType.getSuperclass() == Number.class
\t\t\t \t\t|| fieldType == java.util.Date.class || fieldType == java.sql.Date.class){
\t\t\t \t
\t\t\t \tobj = 0;
\t\t\t }else{
\t\t\t \t
\t\t\t \tobj = "";
\t\t\t }
\t\t\t}
\t\t\t
\t\t\treturn obj;
\t\t\t
\t\t}catch (Exception e) {
\t\t\t
\t\t\treturn PropertyUtils.getProperty(bean, field);
\t\t}
\t}
}

/<string>/<string>/<string>/<string>/<string>/<string>/<size>/<string>/<string>/<string>/<string>/<string>/<string>/<string>
/<string>/<string>
/<class>/<class>/<code>


Java操作bean、屬性、方法的使用工具類


分享到:


相關文章: