find Field by name - Android java.lang.reflect

Android examples for java.lang.reflect:Field Name

Description

find Field by name

Demo Code


//package com.java2s;

import java.lang.reflect.Field;

public class Main {
    public static Field findField(Class<?> cls, String name)
            throws NoSuchFieldException {
        try {//from  w  ww.j a va2s .  c  om
            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