通过反射获取常量值
一:通过反射获取常量值,项目中有个需求需要将请求信息封装到javaBean中
但是请求信息比较特殊,需要通过编码去获取,而且编码是定义在接口类中的常量,所以为了方便
特别把这块功能封装起来
1:定义的常量
1 /** 2 * 3 */ 4 package com.hlcui.entity; 5 6 /** 7 * @author Administrator 8 * 9 */ 10 public interface ConstantsUtil { 11 12 public static interface TeamFundMgr{ 13 public static final int id = 111; 14 public static final String name = "李白"; 15 public static final double salary = 15000.000; 16 } 17 18 }
2:javaBean类
1 /** 2 * 3 */ 4 package com.hlcui.entity; 5 6 /** 7 * @author Administrator 8 * 9 */ 10 public class Person { 11 12 private int id; 13 14 private String name; 15 16 private double salary; 17 18 private String mgr; 19 20 public int getId() { 21 return id; 22 } 23 24 public void setId(int id) { 25 this.id = id; 26 } 27 28 public double getSalary() { 29 return salary; 30 } 31 32 public void setSalary(double salary) { 33 this.salary = salary; 34 } 35 36 public String getMgr() { 37 return mgr; 38 } 39 40 public void setMgr(String mgr) { 41 this.mgr = mgr; 42 } 43 44 public String getName() { 45 return name; 46 } 47 48 49 public void setName(String name) { 50 this.name = name; 51 } 52 53 @Override 54 public String toString() { 55 return "Person [id=" + id + ", name=" + name + ", salary=" + salary + ", mgr=" + mgr + "]"; 56 } 57 58 }
3:转换以及测试方法
1 /** 2 * 3 */ 4 package com.hlcui.test; 5 6 import java.beans.BeanInfo; 7 import java.beans.Introspector; 8 import java.beans.PropertyDescriptor; 9 import java.lang.reflect.Field; 10 import java.lang.reflect.Method; 11 12 import com.hlcui.entity.ConstantsUtil; 13 import com.hlcui.entity.Person; 14 15 /** 16 * @author Administrator 17 * 18 */ 19 public class TestOperateConstant { 20 21 private static final String EXCLUDE_FIELD = "class"; 22 23 public static void main(String[] args) throws Exception { 24 Person person = toBean(new Person()); 25 System.out.println(person); 26 } 27 28 public static <T> T toBean(T t){ 29 Class<?> clazz = t.getClass(); 30 try { 31 BeanInfo beanInfo = Introspector.getBeanInfo(clazz); 32 PropertyDescriptor[] props = beanInfo.getPropertyDescriptors(); 33 for(PropertyDescriptor property:props){ 34 String field = property.getName(); 35 if(EXCLUDE_FIELD.equals(field)){ 36 continue; 37 } 38 Method method = property.getWriteMethod(); 39 method.invoke(t,getValue(field,ConstantsUtil.TeamFundMgr.class)); 40 } 41 } catch (Exception e) { 42 e.printStackTrace(); 43 } 44 return t; 45 } 46 47 public static Object getValue(String fieldName,Class<?> clazz)throws Exception{ 48 Field[] fields = clazz.getDeclaredFields(); 49 for(Field field:fields){ 50 String name = field.getName(); 51 if(fieldName.equals(name)){ 52 return field.get(clazz); 53 } 54 } 55 return null; 56 } 57 }
4:运行结果
1 Person [id=111, name=李白, salary=15000.0, mgr=null]