Java Reflection Field Find findField(Class cls, String fieldName)

Here you can find the source of findField(Class cls, String fieldName)

Description

Try find a field with given name.

License

Apache License

Parameter

Parameter Description
cls the cls
fieldName the field name

Return

the field

Declaration

public static Field findField(Class<?> cls, String fieldName) 

Method Source Code

//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

import java.lang.reflect.Field;

public class Main {
    /**/*from w  w  w.ja v  a 2  s .c  o m*/
     * Find a field of given bean.
     *
     * @param bean the bean
     * @param fieldName the field name
     * @return null if not found
     */
    public static Field findField(Object bean, String fieldName) {
        return findField(bean.getClass(), fieldName);
    }

    /**
     * Try find a field with given name. Goes throw class hierarchie.
     *
     * @param cls the cls
     * @param fieldName the field name
     * @return the field
     */
    public static Field findField(Class<?> cls, String fieldName) {
        Field f = null;
        try {
            f = cls.getDeclaredField(fieldName);
        } catch (SecurityException ex) {
        } catch (NoSuchFieldException ex) {
        }
        if (f != null) {
            return f;
        }
        if (cls == Object.class || cls.getSuperclass() == null) {
            return null;
        }
        return findField(cls.getSuperclass(), fieldName);
    }
}

Related

  1. findField(Class clazz, String name)
  2. findField(Class clazz, String name)
  3. findField(Class clazz, String propName)
  4. findField(Class clazz, String targetName, Class targetType, boolean checkInheritance, boolean strictType)
  5. findField(Class cls, String fieldName)
  6. findField(Class cls, String fieldName)
  7. findField(Class currentClass, String fieldName)
  8. findField(Class inClass, String fieldName)
  9. findField(Class klass, String name)