Android Class Field Find findFirstFieldByExactType(Class clazz, Class type)

Here you can find the source of findFirstFieldByExactType(Class clazz, Class type)

Description

Returns the first field of the given type in a class.

Declaration

public static Field findFirstFieldByExactType(Class<?> clazz,
        Class<?> type) 

Method Source Code

//package com.java2s;

import java.lang.reflect.Field;

public class Main {
    /**//ww w. ja  v a2 s  . c o  m
     * Returns the first field of the given type in a class.
     * Might be useful for Proguard'ed classes to identify fields with unique types.
     * If no matching field was not found, a {@link NoSuchFieldError} will be thrown.
     */
    public static Field findFirstFieldByExactType(Class<?> clazz,
            Class<?> type) {
        Class<?> clz = clazz;
        do {
            for (Field field : clz.getDeclaredFields()) {
                if (field.getType() == type) {
                    field.setAccessible(true);
                    return field;
                }
            }
        } while ((clz = clz.getSuperclass()) != null);

        throw new NoSuchFieldError("Field of type " + type.getName()
                + " in class " + clazz.getName());
    }
}

Related

  1. findField(Class clazz, String fieldName)
  2. findFieldRecursiveImpl(Class clazz, String fieldName)
  3. getAdditionalStaticField(Class clazz, String key)
  4. getFields(Class cs)