Here you can find the source of findField(Class> clazz, String targetName, Class> targetType, boolean checkInheritance, boolean strictType)
public static Field findField(Class<?> clazz, String targetName, Class<?> targetType, boolean checkInheritance, boolean strictType) throws NoSuchFieldException
//package com.java2s; // are made available under the terms of the Eclipse Public License v1.0 import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Modifier; public class Main { public static Field findField(Class<?> clazz, String targetName, Class<?> targetType, boolean checkInheritance, boolean strictType) throws NoSuchFieldException { if (clazz == null) throw new NoSuchFieldException("No class"); if (targetName == null) throw new NoSuchFieldException("No field name"); try {/*from w w w . j a v a2 s .co m*/ Field field = clazz.getDeclaredField(targetName); if (strictType) { if (field.getType().equals(targetType)) return field; } else { if (field.getType().isAssignableFrom(targetType)) return field; } if (checkInheritance) { return findInheritedField(clazz.getPackage(), clazz.getSuperclass(), targetName, targetType, strictType); } else throw new NoSuchFieldException("No field with name " + targetName + " in class " + clazz.getName() + " of type " + targetType); } catch (NoSuchFieldException e) { return findInheritedField(clazz.getPackage(), clazz.getSuperclass(), targetName, targetType, strictType); } } protected static Field findInheritedField(Package pack, Class<?> clazz, String fieldName, Class<?> fieldType, boolean strictType) throws NoSuchFieldException { if (clazz == null) throw new NoSuchFieldException("No class"); if (fieldName == null) throw new NoSuchFieldException("No field name"); try { Field field = clazz.getDeclaredField(fieldName); if (isInheritable(pack, field) && isTypeCompatible(fieldType, field.getType(), strictType)) return field; else return findInheritedField(clazz.getPackage(), clazz.getSuperclass(), fieldName, fieldType, strictType); } catch (NoSuchFieldException e) { return findInheritedField(clazz.getPackage(), clazz.getSuperclass(), fieldName, fieldType, strictType); } } public static boolean isInheritable(Package pack, Member member) { if (pack == null) return false; if (member == null) return false; int modifiers = member.getModifiers(); if (Modifier.isPublic(modifiers)) return true; if (Modifier.isProtected(modifiers)) return true; if (!Modifier.isPrivate(modifiers) && pack.equals(member.getDeclaringClass().getPackage())) return true; return false; } public static boolean isTypeCompatible(Class<?> formalType, Class<?> actualType, boolean strict) { if (formalType == null) return actualType == null; if (actualType == null) return false; if (strict) return formalType.equals(actualType); else return formalType.isAssignableFrom(actualType); } }