find Field without throwing exception - Android java.lang.reflect

Android examples for java.lang.reflect:Field

Description

find Field without throwing exception

Demo Code


//package com.java2s;

import java.lang.reflect.Field;

public class Main {
    public static Field findFieldNoThrow(Class<?> cls, String name) {
        Field f = null;//from w  ww. j  a  v a 2s. com
        try {
            f = findField(cls, name);
        } catch (NoSuchFieldException e) {
        }
        return f;
    }

    public static Field findField(Class<?> cls, String name)
            throws NoSuchFieldException {
        try {
            Field m = cls.getField(name);
            if (m != null) {
                return m;
            }
        } catch (Exception e) {
            // ignore this error & pass down
        }

        Class<?> clsType = cls;
        while (clsType != null) {
            try {
                Field m = clsType.getDeclaredField(name);
                m.setAccessible(true);
                return m;
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
            clsType = clsType.getSuperclass();
        }
        throw new NoSuchFieldException();
    }
}

Related Tutorials