Java examples for Reflection:Field Value
get Value By Field Type
//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; } }