黑马程序员技术交流社区

标题: 【石家庄校区】反射 [打印本页]

作者: ,喵了个咪    时间: 2019-5-19 10:16
标题: 【石家庄校区】反射
本帖最后由 小石姐姐 于 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;
}






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2