A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© ,喵了个咪 初级黑马   /  2019-5-19 10:16  /  773 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 小石姐姐 于 2019-5-24 10:41 编辑

Java中反射获取类的值
[Java] 纯文本查看 复制代码
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 
import java.lang.reflect.*; 
import com.dragance.hrcrm.persist.PublicFiled; 

/** 
*通过反射获得所有字段的值和字段 
* @param publicFiled 类对象 
* @return 
*/ 
public Map<String,Object> getPublicFiledMap(PublicFiled publicFiled) { 
   Map<String,Object> filedMap = new HashMap<String,Object>(); 
   //反射publicFiled类的所有字段 
   Class cla = publicFiled.getClass(); 

   //获得该类下面所有的字段集合 
   Field[] filed = cla.getDeclaredFields(); 
   for(Field fd : filed) { 
      String filedName = fd.getName(); 
      String firstLetter = filedName.substring(0,1).toUpperCase(); //获得字段第一个字母大写 
       String getMethodName = "get"+firstLetter+filedName.substring(1); //转换成字段的get方法 

       try { 
      Method getMethod = cla.getMethod(getMethodName, new Class[] {}); 
      Object value = getMethod.invoke(publicFiled, new Object[] {}); //这个对象字段get方法的值 

      filedMap.put(filedName, value); //添加到Map集合 

   } catch (SecurityException e) { 
e.printStackTrace(); 
   } catch (NoSuchMethodException e) { 
e.printStackTrace(); 
   } catch (IllegalArgumentException e) { 
e.printStackTrace(); 
   } catch (IllegalAccessException e) { 
e.printStackTrace(); 
   } catch (InvocationTargetException e) { 
e.printStackTrace(); 
   } 

   } 
return filedMap; 
} 

/** 
*通过反射获得所有字段的值和字段 
* @param publicFiled 类对象对象 
* @param filedName 字段名称 
* @return 
*/ 
public Object getPublicFiledMap(PublicFiled publicFiled,String filedName) { 
   Object value = null; 
//反射publicFiled类的所有字段 
   Class cla = publicFiled.getClass(); 
   try { 
   Field field = cla.getDeclaredField(filedName); 
   String firstLetter = field.getName().substring(0,1).toUpperCase(); //获得字段第一个字母大写 
   String getMethodName = "get"+firstLetter+field.getName().substring(1); //转换成字段的get方法 


   try { 
   Method getMethod = cla.getMethod(getMethodName, new Class[] {}); 
   value = getMethod.invoke(publicFiled, new Object[] {}); //这个对象字段get方法的值 

   } catch (SecurityException e) { 
e.printStackTrace(); 
   } catch (NoSuchMethodException e) { 
e.printStackTrace(); 
   } catch (IllegalArgumentException e) { 
e.printStackTrace(); 
   } catch (IllegalAccessException e) { 
e.printStackTrace(); 
   } catch (InvocationTargetException e) { 
e.printStackTrace(); 
   } 

   } catch (SecurityException e) { 
   e.printStackTrace(); 
   } catch (NoSuchFieldException e) { 
      e.printStackTrace(); 
   } 

   return value; 
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马