java反射字段属性顺序,java反射根据字段名读取值

import java.lang.reflect.Field;

/**

* @author Administrator

* 反射工具

*/

public class ReflectHelper {

/**

* 获取obj对象fieldName的Field

* @param obj

* @param fieldName

* @return

*/

public static Field getFieldByFieldName(Object obj, String fieldName) {

for (Class> superClass = obj.getClass(); superClass != Object.class; superClass = superClass

.getSuperclass()) {

try {

return superClass.getDeclaredField(fieldName);

} catch (NoSuchFieldException e) {

}

}

return null;

}

/**

* 获取obj对象fieldName的属性值

* @param obj

* @param fieldName

* @return

* @throws SecurityException

* @throws NoSuchFieldException

* @throws IllegalArgumentException

* @throws IllegalAccessException

*/

public static Object getValueByFieldName(Object obj, String fieldName)

throws SecurityException, NoSuchFieldException,

IllegalArgumentException, IllegalAccessException {

Field field = getFieldByFieldName(obj, fieldName);

Object value = null;

if(field!=null){

if (field.isAccessible()) {

value = field.get(obj);

} else {

field.setAccessible(true);

value = field.get(obj);

field.setAccessible(false);

}

}

return value;

}

/**

* 设置obj对象fieldName的属性值

* @param obj

* @param fieldName

* @param value

* @throws SecurityException

* @throws NoSuchFieldException

* @throws IllegalArgumentException

* @throws IllegalAccessException

*/

public static void setValueByFieldName(Object obj, String fieldName,

Object value) throws SecurityException, NoSuchFieldException,

IllegalArgumentException, IllegalAccessException {

Field field = obj.getClass().getDeclaredField(fieldName);

if (field.isAccessible()) {

field.set(obj, value);

} else {

field.setAccessible(true);

field.set(obj, value);

field.setAccessible(false);

}

}

/**

* 测试主函数

* @param args

*/

public static void main(String[] args) {

try {

Class cls = Class.forName("com.flf.entity.User");

Field field;

try {

// 得到一个类的实例

Object user = cls.newInstance();

// 调用根据字段名得到字段的方法

field = ReflectHelper.getFieldByFieldName(user, "loginname");

System.out.println(field.getName());

// 根据字段名给字段赋值

ReflectHelper.setValueByFieldName(user, "loginname","admin");

// 根据字段名获取到字段值

Object nameValue = ReflectHelper.getValueByFieldName(user, "loginname");

System.out.println(nameValue);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值