| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | |
|
| 6 | |
|
| 7 | |
|
| 8 | |
|
| 9 | |
|
| 10 | |
|
| 11 | |
|
| 12 | |
|
| 13 | |
|
| 14 | |
|
| 15 | |
|
| 16 | |
|
| 17 | |
package org.truth0.util; |
| 18 | |
|
| 19 | |
import com.google.common.annotations.GwtIncompatible; |
| 20 | |
import java.lang.reflect.Field; |
| 21 | |
import java.lang.reflect.ParameterizedType; |
| 22 | |
import java.lang.reflect.Type; |
| 23 | |
|
| 24 | |
|
| 25 | |
|
| 26 | |
|
| 27 | |
|
| 28 | |
|
| 29 | |
@GwtIncompatible("java.lang.reflect.*") |
| 30 | 0 | public class ReflectionUtil { |
| 31 | |
|
| 32 | |
|
| 33 | |
public static Class<?> typeParameter(Class<?> clazz, int paramIndex) { |
| 34 | 10 | Type superclass = clazz.getGenericSuperclass(); |
| 35 | 10 | if (!(superclass instanceof ParameterizedType)) { |
| 36 | 0 | throw new IllegalArgumentException ("" + superclass + " isn't parameterized"); |
| 37 | |
} |
| 38 | 10 | Type[] typeParams = ((ParameterizedType) superclass).getActualTypeArguments(); |
| 39 | 10 | return (Class<?>)typeParams[paramIndex]; |
| 40 | |
} |
| 41 | |
|
| 42 | |
public static Field getField(Class<?> clazz, String fieldName) throws NoSuchFieldException { |
| 43 | 12 | Class<?> currentClass = clazz; |
| 44 | 18 | while (currentClass != null) { |
| 45 | |
try { |
| 46 | 15 | return clazz.getDeclaredField(fieldName); |
| 47 | 6 | } catch (NoSuchFieldException e) { |
| 48 | 6 | currentClass = currentClass.getSuperclass(); |
| 49 | 6 | } |
| 50 | |
} |
| 51 | 3 | throw new NoSuchFieldException("No such field " + fieldName + " declared on " + |
| 52 | |
clazz.getSimpleName() + " or its parent classes."); |
| 53 | |
} |
| 54 | |
} |