Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
 package com.cantaa.util;

Hans Lesmeister
 public class ReflectionUtil {
    public static void setFieldValue(Object targetString fieldNameObject value) {
        Field fld = findField(target.getClass(), fieldNamenull);
        if (fld == null) {
        if (!fld.isAccessible()) {
        try {
        catch (IllegalAccessException e) {
            throw new RuntimeException(e);

Attempt to find a field on the supplied java.lang.Class with the supplied name and/or type. Searches all superclasses up to java.lang.Object.

(Borrowed from Spring)

clazz the class to introspect
name the name of the field (may be null if type is specified)
type the type of the field (may be null if name is specified)
the corresponding Field object, or null if not found
    public static Field findField(Class<?> clazzString nameClass<?> type) {
        Reject.ifNull(clazz"Class must not be null");
        Reject.ifFalse(name != null || type != null"Either name or type of the field must be specified");
        Class<?> searchType = clazz;
        while (!Object.class.equals(searchType) && searchType != null) {
            Field[] fields = searchType.getDeclaredFields();
            for (Field field : fields) {
                if ((name == null || name.equals(field.getName())) && (type == null || type.equals(field.getType()))) {
                    return field;
            searchType = searchType.getSuperclass();
        return null;
New to GrepCode? Check out our FAQ X