集册 Java实例教程 通过字段名称获取值

通过字段名称获取值

欢马劈雪     最近更新时间:2020-01-02 10:19:05

369
通过字段名称获取值
/**
 from
* n o w j a v a . c o m 
**/


//package com.nowjava;

import java.lang.reflect.Field;


public class Main {


    public static Object getValueByFieldName(Object obj, String fieldName) {

        Object value = null;

        try {

            Field field = getFieldByFieldName(obj, fieldName);

            if (field != null) {

                if (field.isAccessible()) {

                    value = field.get(obj);/* 来 自 N o w J a v a . c o m*/

                } else {

                    field.setAccessible(true);

                    value = field.get(obj);

                    field.setAccessible(false);

                }

            }

        } catch (Exception e) {

        }

        return value;

    }


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

        if (obj == null || fieldName == null) {

            return null;

        }

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

                .getSuperclass()) {
展开阅读全文