`
china_jianchen
  • 浏览: 61729 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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;
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics