Here you can find the source of findField(Class clazz, String fieldName)
public static Field findField(Class clazz, String fieldName)
//package com.java2s; /**/*from w w w .j a v a 2 s. co m*/ * Copyright 2010 Google Inc. * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. **/ import java.lang.reflect.*; import java.util.*; public class Main { public static Field findField(Class clazz, String fieldName) { Vector<Field> fields = new Vector<Field>(); getField(fields, clazz, fieldName); if (fields.size() == 0) { throw new RuntimeException( "ClassHelper.findField: Could not find Field with name for given Class -- ClassName: " + clazz.getName() + " -- FieldName: " + fieldName); } if (fields.size() != 1) { throw new RuntimeException( "ClassHelper.findField: Could not find Field with name for given Class -- ClassName: " + clazz.getClass().getName() + " -- FieldName: " + fieldName); } return (fields.get(0)); } private static void getField(Vector<Field> inVector, Class clazz, String fieldName) { if (clazz == null) { return; } getField(inVector, clazz.getSuperclass(), fieldName); Field[] classFields = clazz.getDeclaredFields(); for (Field field : classFields) { if (!(field.getName().equals(fieldName) && isStaticFinal(field))) { continue; } field.setAccessible(true); inVector.add(field); } } /** * Get the underlying class for a type, or null if the type is a variable * type. * * @param type the type * @return the underlying class */ public static Class<?> getClass(Type type) { if (type instanceof Class) { return (Class) type; } else if (type instanceof ParameterizedType) { return getClass(((ParameterizedType) type).getRawType()); } else if (type instanceof GenericArrayType) { Type componentType = ((GenericArrayType) type).getGenericComponentType(); Class<?> componentClass = getClass(componentType); if (componentClass != null) { return Array.newInstance(componentClass, 0).getClass(); } else { return null; } } else { return null; } } private static boolean isStaticFinal(Field f) { int mods = f.getModifiers(); return Modifier.isStatic(mods) || Modifier.isFinal(mods); } }