标签:style blog io ar color os sp for java
1 package com.lovo.util; 2 3 import java.lang.reflect.Constructor; 4 import java.lang.reflect.Field; 5 6 public class MyUtil { 7 private MyUtil(){ 8 throw new AssertionError(); 9 } 10 /** 11 * 通过反射获取对象的字段值 12 * @param target 目标对象 13 * @param fieldName 字段名称 14 * @return 字段的值或null 15 */ 16 public static Object getValue(Object target,String fieldName) { 17 Object value = null; 18 //用"."分割例如:"car.engine"表示target对象的(Car类型)car属性的(Engine)engine属性值 19 String[] strs = fieldName.split("\\."); 20 for (int i = 0; i < strs.length; i++) { 21 if (target != null) { 22 try { 23 Class<?> clazz = target.getClass();//得到target对象类的类类型对象(描述target对象类的类对象) 24 Field f = clazz.getDeclaredField(strs[i]);//得到属性 25 f.setAccessible(true); 26 if (i == strs.length - 1) { 27 value = f.get(target);//得到属性值 28 return value; 29 } else { 30 target = f.get(target);//修改target 31 } 32 } catch (Exception e) { 33 throw new RuntimeException(e); 34 } 35 } 36 } 37 return null; 38 } 39 /** 40 * 设置属性值 41 * @param target 目标对象 42 * @param fieldName 属性 43 * @param value 值 44 */ 45 public static void setValue(Object target,String fieldName,Object value) { 46 Class<?> clazz = target.getClass(); 47 String[] trs = fieldName.split("\\."); 48 for (int i = 0; i < trs.length - 1; i++) { 49 try { 50 Field f = clazz.getDeclaredField(trs[i]); 51 f.setAccessible(true); 52 // Object tempTarget = target; 53 // target = f.get(target); 54 if (f.get(target) == null) { 55 String type = f.getGenericType().toString();//得到值为null的属性的类型的字符串 56 String[] typeSplits = type.split(" "); 57 clazz = Class.forName(typeSplits[1]);//得到值为null的属性的类型的类类型对象 58 Constructor<?> con = clazz.getDeclaredConstructor();//得到属性的无参构造器 59 con.setAccessible(true); //有可能是private的所以设置可以访问 60 f.set(target, con.newInstance());//给null属性赋值 61 } 62 target = f.get(target); 63 clazz = target.getClass(); 64 65 } catch (Exception e) { 66 e.printStackTrace(); 67 throw new RuntimeException(); 68 } 69 } 70 try { 71 Field f = clazz.getDeclaredField(trs[trs.length - 1]); 72 f.setAccessible(true); 73 f.set(target, value); 74 75 } catch (Exception e) { 76 throw new RuntimeException(); 77 } 78 } 79 }
标签:style blog io ar color os sp for java
原文地址:http://www.cnblogs.com/f644135318/p/4148559.html