Java Reflection Field Find findFields(Class type)

Here you can find the source of findFields(Class type)

Description

Loads or fetches from the cache a Map of Field objects keyed into the Map by the field name they correspond to.

License

Open Source License

Parameter

Parameter Description
type The class to grab the fields from.

Return

The Map, which could be null if the class has no fields.

Declaration

public static Map<String, Field> findFields(Class<?> type) 

Method Source Code

//package com.java2s;
/*/*from  w  w  w . j  a v  a2  s.com*/
 * Copyright (c) 2012, Inversoft Inc., All Rights Reserved
 *
 * 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.*;

public class Main {
    private static final Map<Class<?>, Map<String, Field>> fieldCache = new WeakHashMap<Class<?>, Map<String, Field>>();

    /**
     * Loads or fetches from the cache a Map of {@link Field} objects keyed into the Map by the field name they correspond
     * to.
     *
     * @param type The class to grab the fields from.
     * @return The Map, which could be null if the class has no fields.
     */
    public static Map<String, Field> findFields(Class<?> type) {
        Map<String, Field> fieldMap;
        synchronized (fieldCache) {
            // Otherwise look for the property Map or create and store
            fieldMap = fieldCache.get(type);
            if (fieldMap != null) {
                return fieldMap;
            }

            fieldMap = new HashMap<String, Field>();
            Field[] fields = type.getFields();
            for (Field field : fields) {
                fieldMap.put(field.getName(), field);
            }

            fieldCache.put(type, Collections.unmodifiableMap(fieldMap));
        }

        return fieldMap;
    }
}

Related

  1. findFieldInternal(Class currentClass, Class annotation, Set fields)
  2. findFieldOfBean(Object bean, String fieldName)
  3. findFieldOfTypeInClass(final Class source, final Class type)
  4. findFieldRecursively(Class c, String fieldName)
  5. findFields(Class c, boolean allowTransient, int max, Iterable> fieldClassesToFind, Iterable> exceptClasses)
  6. findFields(final Class clazz, final Predicate filter)
  7. findFieldsAnnotatedWith(Class annotation, Class parentClass)
  8. findFieldsAnnotatedWith(final Class type, final Class annotation)
  9. findFieldsOfClass(Class target, Object o, String path, Logger log, Set done)