(Object obj, Class<T> type)
| 1085 | } |
| 1086 | |
| 1087 | public static <T> T getFirstByType(Object obj, Class<T> type) throws NoSuchFieldException { |
| 1088 | if (obj == null) { |
| 1089 | throw new NullPointerException("obj == null"); |
| 1090 | } |
| 1091 | if (type == null) { |
| 1092 | throw new NullPointerException("type == null"); |
| 1093 | } |
| 1094 | Class<?> clz = obj.getClass(); |
| 1095 | while (clz != null && !clz.equals(Object.class)) { |
| 1096 | for (Field f : clz.getDeclaredFields()) { |
| 1097 | if (!f.getType().equals(type)) { |
| 1098 | continue; |
| 1099 | } |
| 1100 | f.setAccessible(true); |
| 1101 | try { |
| 1102 | return (T) f.get(obj); |
| 1103 | } catch (IllegalAccessException ignored) { |
| 1104 | // should not happen |
| 1105 | } |
| 1106 | } |
| 1107 | clz = clz.getSuperclass(); |
| 1108 | } |
| 1109 | throw new NoSuchFieldException("No field of type " + type.getName() + " found in " |
| 1110 | + obj.getClass().getName() + " and superclasses"); |
| 1111 | } |
| 1112 | |
| 1113 | public static <T> T getFirstByTypeOrNull(Object obj, Class<T> type) { |
| 1114 | try { |
no test coverage detected