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

通过字段名称获取字段

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

475
通过字段名称获取字段
/*来自 n o w j a v a . c o m*/

//package com.nowjava;

import java.lang.reflect.Field;


public class Main {

    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;

    }

}