在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

通过Java反射机制,动态给对象属性赋值,并获取属性值

2016-12-20 13:16| 发布者: zhangjf| 查看: 609| 评论: 0

摘要: import java.lang.reflect.Field;import java.lang.reflect.Method;import java.text.SimpleDateFormat;import java.util.Date;import java.util.HashMap;import java.util.Locale;import java.util.Map;import java ...
  1. import java.lang.reflect.Field;
  2. import java.lang.reflect.Method;
  3. import java.text.SimpleDateFormat;
  4. import java.util.Date;
  5. import java.util.HashMap;
  6. import java.util.Locale;
  7. import java.util.Map;
  8. import java.util.Map.Entry;
  9. /*
  10. * 通过Java反射机制,动态给对象属性赋值,并获取属性值
  11. */
  12. public class ClassRefUtil {
  13. /**
  14. * @param args
  15. */
  16. public static void main(String[] args) {
  17. Map<String, String> valMap = new HashMap<String, String>();
  18. valMap.put("userName", "michael");
  19. valMap.put("age", "27");
  20. valMap.put("height", "173.5");
  21. valMap.put("date", "2010-10-24");
  22. valMap.put("times", "1287932898276");
  23. valMap.put("flag", "false");
  24. ChildInfo rl = new ChildInfo();
  25. System.out.println("通过反射赋值.");
  26. PublicUtil.setFieldValue(rl, valMap);
  27. System.out.println("通过反射取值:");
  28. int i = 0;
  29. Map<String, String> fieldValMap = PublicUtil.getFieldValueMap(rl);
  30. for (Entry<String, String> entry : fieldValMap.entrySet()) {
  31. i++;
  32. System.out.println("[字段 "+i+"] ["+entry.getKey()+"] --- [" + entry.getValue()+"]");
  33. }
  34. }
  35. /**
  36. * 取Bean的属性和值对应关系的MAP
  37. * @param bean
  38. * @return Map
  39. */
  40. public static Map<String, String> getFieldValueMap(Object bean) {
  41. Class<?> cls = bean.getClass();
  42. Map<String, String> valueMap = new HashMap<String, String>();
  43. // 取出bean里的所有方法
  44. Method[] methods = cls.getDeclaredMethods();
  45. Field[] fields = cls.getDeclaredFields();
  46. for (Field field : fields) {
  47. try {
  48. String fieldType = field.getType().getSimpleName();
  49. String fieldGetName = parGetName(field.getName());
  50. if (!checkGetMet(methods, fieldGetName)) {
  51. continue;
  52. }
  53. Method fieldGetMet = cls.getMethod(fieldGetName, new Class[] {});
  54. Object fieldVal = fieldGetMet.invoke(bean, new Object[] {});
  55. String result = null;
  56. if ("Date".equals(fieldType)) {
  57. result = fmtDate((Date) fieldVal);
  58. } else {
  59. if (null != fieldVal) {
  60. result = String.valueOf(fieldVal);
  61. }
  62. }
  63. valueMap.put(field.getName(), result);
  64. } catch (Exception e) {
  65. continue;
  66. }
  67. }
  68. return valueMap;
  69. }
  70. /**
  71. * set属性的值到Bean
  72. * @param bean
  73. * @param valMap
  74. */
  75. public static void setFieldValue(Object bean, Map<String, String> valMap) {
  76. Class<?> cls = bean.getClass();
  77. // 取出bean里的所有方法
  78. Method[] methods = cls.getDeclaredMethods();
  79. Field[] fields = cls.getDeclaredFields();
  80. for (Field field : fields) {
  81. try {
  82. String fieldSetName = parSetName(field.getName());
  83. if (!checkSetMet(methods, fieldSetName)) {
  84. continue;
  85. }
  86. Method fieldSetMet = cls.getMethod(fieldSetName, field.getType());
  87. String value = valMap.get(field.getName());
  88. if (null != value && !"".equals(value)) {
  89. String fieldType = field.getType().getSimpleName();
  90. if ("String".equals(fieldType)) {
  91. fieldSetMet.invoke(bean, value);
  92. } else if ("Date".equals(fieldType)) {
  93. Date temp = parseDate(value);
  94. fieldSetMet.invoke(bean, temp);
  95. } else if ("Integer".equals(fieldType) || "int".equals(fieldType)) {
  96. Integer intval = Integer.parseInt(value);
  97. fieldSetMet.invoke(bean, intval);
  98. } else if ("Long".equalsIgnoreCase(fieldType)) {
  99. Long temp = Long.parseLong(value);
  100. fieldSetMet.invoke(bean, temp);
  101. } else if ("Double".equalsIgnoreCase(fieldType)) {
  102. Double temp = Double.parseDouble(value);
  103. fieldSetMet.invoke(bean, temp);
  104. } else if ("Boolean".equalsIgnoreCase(fieldType)) {
  105. Boolean temp = Boolean.parseBoolean(value);
  106. fieldSetMet.invoke(bean, temp);
  107. } else {
  108. System.out.println("not supper type" + fieldType);
  109. }
  110. }
  111. } catch (Exception e) {
  112. continue;
  113. }
  114. }
  115. }
  116. /**
  117. * 格式化string为Date
  118. * @param datestr
  119. * @return date
  120. */
  121. private static Date parseDate(String datestr) {
  122. if (null == datestr || "".equals(datestr)) {
  123. return null;
  124. }
  125. try {
  126. String fmtstr = null;
  127. if (datestr.indexOf(':') > 0) {
  128. fmtstr = "yyyy-MM-dd HH:mm:ss";
  129. } else {
  130. fmtstr = "yyyy-MM-dd";
  131. }
  132. SimpleDateFormat sdf = new SimpleDateFormat(fmtstr, Locale.UK);
  133. return sdf.parse(datestr);
  134. } catch (Exception e) {
  135. return null;
  136. }
  137. }
  138. /**
  139. * 日期转化为String
  140. * @param date
  141. * @return date string
  142. */
  143. private static String fmtDate(Date date) {
  144. if (null == date) {
  145. return null;
  146. }
  147. try {
  148. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
  149. return sdf.format(date);
  150. } catch (Exception e) {
  151. return null;
  152. }
  153. }
  154. /**
  155. * 判断是否存在某属性的 set方法
  156. * @param methods
  157. * @param fieldSetMet
  158. * @return boolean
  159. */
  160. private static boolean checkSetMet(Method[] methods, String fieldSetMet) {
  161. for (Method met : methods) {
  162. if (fieldSetMet.equals(met.getName())) {
  163. return true;
  164. }
  165. }
  166. return false;
  167. }
  168. /**
  169. * 判断是否存在某属性的 get方法
  170. * @param methods
  171. * @param fieldGetMet
  172. * @return boolean
  173. */
  174. private static boolean checkGetMet(Method[] methods, String fieldGetMet) {
  175. for (Method met : methods) {
  176. if (fieldGetMet.equals(met.getName())) {
  177. return true;
  178. }
  179. }
  180. return false;
  181. }
  182. /**
  183. * 拼接某属性的 get方法
  184. * @param fieldName
  185. * @return String
  186. */
  187. private static String parGetName(String fieldName) {
  188. if (null == fieldName || "".equals(fieldName)) {
  189. return null;
  190. }
  191. return "get" + fieldName.substring(0, 1).toUpperCase()
  192. + fieldName.substring(1);
  193. }
  194. /**
  195. * 拼接在某属性的 set方法
  196. * @param fieldName
  197. * @return String
  198. */
  199. private static String parSetName(String fieldName) {
  200. if (null == fieldName || "".equals(fieldName)) {
  201. return null;
  202. }
  203. return "set" + fieldName.substring(0, 1).toUpperCase()
  204. + fieldName.substring(1);
  205. }
  206. }
复制代码

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-8 15:04

Copyright 2015-2025 djqfx

返回顶部