get Value By Field Type - Java Reflection

Java examples for Reflection:Field Value

Description

get Value By Field Type

Demo Code


//package com.java2s;
import java.lang.reflect.Field;

public class Main {

    @SuppressWarnings("unchecked")
    public static <T> T getValueByFieldType(Object obj, Class<T> fieldType) {
        Object value = null;/*from  ww w .jav  a2 s .  co m*/
        for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass
                .getSuperclass()) {
            try {
                Field[] fields = superClass.getDeclaredFields();
                for (Field f : fields) {
                    if (f.getType() == fieldType) {
                        if (f.isAccessible()) {
                            value = f.get(obj);
                            break;
                        } else {
                            f.setAccessible(true);
                            value = f.get(obj);
                            f.setAccessible(false);
                            break;
                        }
                    }
                }
                if (value != null) {
                    break;
                }
            } catch (Exception e) {
            }
        }
        return (T) value;
    }
}

Related Tutorials