Java Reflection Field Find findField(Class clazz, Class type, String name)

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

Description

find Field

License

Apache License

Declaration

public static Field findField(Class clazz, Class type, String name) throws NoSuchFieldException 

Method Source Code


//package com.java2s;
/*/*from   ww w  .  ja  v a  2s . co m*/
 * Copyright 2000-2014 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static Field findField(Class clazz, Class type, String name) throws NoSuchFieldException {
        List<Field> fields = collectFields(clazz);
        for (Field each : fields) {
            if (name.equals(each.getName()) && (type == null || each.getType().equals(type)))
                return each;
        }

        throw new NoSuchFieldException("Class: " + clazz + " name: " + name + " type: " + type);
    }

    public static List<Field> collectFields(Class clazz) {
        List<Field> result = new ArrayList<Field>();
        collectFields(clazz, result);
        return result;
    }

    private static void collectFields(Class clazz, List<Field> result) {
        final Field[] fields = clazz.getDeclaredFields();
        result.addAll(Arrays.asList(fields));
        final Class superClass = clazz.getSuperclass();

        if (superClass != null) {
            collectFields(superClass, result);
        }

        final Class[] interfaces = clazz.getInterfaces();
        for (Class each : interfaces) {
            collectFields(each, result);
        }
    }
}

Related

  1. findField(Class aClass, String aFieldName)
  2. findField(Class c, Class fieldtype)
  3. findField(Class c, String fieldName)
  4. findField(Class classBeFind, String name)
  5. findField(Class classType, String fieldName, Class fieldType)
  6. findField(Class clazz, String fieldName)
  7. findField(Class clazz, String fieldName)
  8. findField(Class clazz, String name)
  9. findField(Class clazz, String name)