Here you can find the source of findField(Class> clazz, String name)
Parameter | Description |
---|---|
clazz | the class to introspect |
name | the name of the field |
public static Field findField(Class<?> clazz, String name)
//package com.java2s; //License from project: Apache License import java.lang.reflect.Field; public class Main { /**/*from w w w .j ava2s .com*/ * Attempt to find a {@link Field field} on the supplied {@link Class} with the * supplied {@code name}. Searches all superclasses up to {@link Object}. * @param clazz the class to introspect * @param name the name of the field * @return the corresponding Field object, or {@code null} if not found */ public static Field findField(Class<?> clazz, String name) { return findField(clazz, name, null); } /** * Attempt to find a {@link Field field} on the supplied {@link Class} with the * supplied {@code name} and/or {@link Class type}. Searches all superclasses * up to {@link Object}. * @param clazz the class to introspect * @param name the name of the field (may be {@code null} if type is specified) * @param type the type of the field (may be {@code null} if name is specified) * @return the corresponding Field object, or {@code null} if not found */ public static Field findField(Class<?> clazz, String name, Class<?> type) { Class<?> searchType = clazz; while (Object.class != searchType && searchType != null) { Field[] fields = getDeclaredFields(searchType); for (Field field : fields) { if ((name == null || name.equals(field.getName())) && (type == null || type.equals(field.getType()))) { return field; } } searchType = searchType.getSuperclass(); } return null; } /** * This variant retrieves {@link Class#getDeclaredFields()} from a local cache * in order to avoid the JVM's SecurityManager check and defensive array copying. * @param clazz the class to introspect * @return the cached array of fields * @see Class#getDeclaredFields() */ private static Field[] getDeclaredFields(Class<?> clazz) { return clazz.getDeclaredFields(); } }