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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值