Java Reflection Field Find findField(Class clazz, String fname, boolean isSearchSuperclass)

Here you can find the source of findField(Class clazz, String fname, boolean isSearchSuperclass)

Description

find Field

License

Open Source License

Declaration

private static Field findField(Class<?> clazz, String fname, boolean isSearchSuperclass)
            throws NoSuchFieldException, AssertionError 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.lang.reflect.Field;

public class Main {
    private static Field findField(Class<?> clazz, String fname, boolean isSearchSuperclass)
            throws NoSuchFieldException, AssertionError {
        Field f = null;//from   w  ww  . j  a  va  2 s  . co  m
        try {
            f = clazz.getDeclaredField(fname);
        } catch (NoSuchFieldException e) {

        }
        if (f == null && isSearchSuperclass) {
            do {
                clazz = clazz.getSuperclass();
                if (clazz == null) {
                    throw new NoSuchFieldException("Class " + clazz + " has no such field: %s" + fname); //$NON-NLS-1$ //$NON-NLS-2$
                }
                try {
                    f = clazz.getDeclaredField(fname);
                } catch (NoSuchFieldException e) {

                }
            } while (f == null);
        }
        return f;
    }

    public static Object getDeclaredField(String name, Object this_) {
        try {
            Field field = this_.getClass().getDeclaredField(name);
            field.setAccessible(true);
            return getField(field, this_);
        } catch (SecurityException e) {
            throw new AssertionError(e);
        } catch (NoSuchFieldException e) {
            throw new AssertionError(e);
        }
    }

    /**
     * Gets value of field in spite of access permission.
     */
    public static Object getField(Field f, Object this_) {
        try {
            f.setAccessible(true);
            return f.get(this_);
        } catch (IllegalAccessException e) {
            throw new AssertionError(e);
        }
    }

    /**
     * Gets value of field in spite of access permission.
     *
     * @throws AssertionError if no such field in the class
     */
    public static Object getField(Class<?> clazz, String fname, Object this_, boolean isSearchSuperclass) {
        try {
            Field f = findField(clazz, fname, isSearchSuperclass);
            return getField(f, this_);
        } catch (NoSuchFieldException e) {
            throw new AssertionError(e);
        }
    }
}

Related

  1. findField(Class clazz, String fieldName)
  2. findField(Class clazz, String fieldName)
  3. findField(Class clazz, String fieldName)
  4. findField(Class clazz, String fieldName)
  5. findField(Class clazz, String fieldName)
  6. findField(Class clazz, String name)
  7. findField(Class clazz, String name)
  8. findField(Class clazz, String name)
  9. findField(Class clazz, String name)