Java Reflection Field Find findField(Class c, String name)

Here you can find the source of findField(Class c, String name)

Description

find Field

License

Open Source License

Declaration

public static Field findField(Class<?> c, String name) 

Method Source Code

//package com.java2s;
/*//from   ww w. ja v a  2 s  .c om
 * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

import java.lang.reflect.Field;

import java.util.HashMap;

import java.util.Map;

public class Main {
    public static Map<String, Field> refFieldsCache = new HashMap<>();

    public static Field findField(Class<?> c, String name) {
        if (c == null) {
            return null;
        }
        String cacheKey = c.getName() + name;
        Field f = refFieldsCache.get(cacheKey);
        if (f != null) {
            return f;
        }

        try {
            f = c.getDeclaredField(name);
            f.setAccessible(true);
            refFieldsCache.put(cacheKey, f);
            return f;
        } catch (Exception err) {
        }

        Class<?> s = c.getSuperclass();
        if (s != null) {
            f = findField(s, name);
            if (f != null) {
                refFieldsCache.put(cacheKey, f);
            }
            return f;
        }
        return null;
    }

    public static Object get(Object o, String name) {
        try {
            Class<?> c = o.getClass();
            Field f = findField(c, name);
            return f.get(o);
        } catch (Exception err) {
            //XSQLAdapter.log(err);
        }
        return null;
    }
}

Related

  1. findField(Class clazz, String name)
  2. findField(Class clazz, String name)
  3. findField(Class cls, String name)
  4. findField(Class objectClass, String fieldName)
  5. findField(Class type, String fieldName)
  6. findField(Class c, String property, Class propertyType)
  7. findField(Class cl, String fieldName)
  8. findField(Class classToCheck, String propertyName)
  9. findField(Class claz, String... names)