Here you can find the source of findField(Class> targetClass, String fieldName)
public static Field findField(Class<?> targetClass, String fieldName)
//package com.java2s; /*/*w ww. jav a 2 s . c om*/ * Copyright 2013-2015 the original author or authors. * * 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.Field; import java.lang.reflect.Method; public class Main { public static Field findField(Object target, String fieldName) { Class<?> clz = target.getClass(); return findField(clz, fieldName); } public static Field findField(Class<?> targetClass, String fieldName) { Field theField; try { theField = targetClass.getDeclaredField(fieldName); return accessible(theField); } catch (NoSuchFieldException e) { if (targetClass.getSuperclass() != null) return findField(targetClass.getSuperclass(), fieldName); else return null; } } public static Field findField(Object obj, String fieldName, Class<?> type) { if (obj == null) return null; Field theField = findField(obj.getClass(), fieldName); if (isFieldType(theField, type)) return theField; return null; } public static Field findField(Class<?> targetClass, String fieldName, Class<?> type) { Field theField = findField(targetClass, fieldName); if (isFieldType(theField, type)) return theField; return null; } public static Method accessible(Method method) { if (method != null) { if (!method.isAccessible()) method.setAccessible(true); } return method; } public static Field accessible(Field theField) { if (theField != null) { if (!theField.isAccessible()) theField.setAccessible(true); } return theField; } public static boolean isFieldType(Field field, Class<?> clz) { if (field != null) { Class<?> type = field.getType(); if (type.isAssignableFrom(clz)) { return true; } } return false; } }