View Javadoc

    1   package sharin.util;
    2
    3   import java.lang.reflect.Field;
    4   import java.lang.reflect.InvocationTargetException;
    5   import java.lang.reflect.Method;
    6
    7   public class ReflectUtils {
    8
    9       public static <T> T newInstance(Class<T> clazz) {
    10
    11          try {
    12              return clazz.newInstance();
    13
    14          } catch (InstantiationException e) {
    15              throw new RuntimeException(e);
    16
    17          } catch (IllegalAccessException e) {
    18              throw new RuntimeException(e);
    19          }
    20      }
    21
    22      @SuppressWarnings("unchecked")
    23      public static <T> T get(Field field, Object object) {
    24
    25          try {
    26              return (T) field.get(object);
    27
    28          } catch (IllegalAccessException e) {
    29              throw new RuntimeException(e);
    30          }
    31      }
    32
    33      public static void set(Field field, Object object, Object value) {
    34
    35          try {
    36              field.set(object, value);
    37
    38          } catch (IllegalAccessException e) {
    39              throw new RuntimeException(e);
    40          }
    41      }
    42
    43      @SuppressWarnings("unchecked")
    44      public static <T> T invoke(Method method, Object obj, Object... args) {
    45
    46          try {
    47              return (T) method.invoke(obj, args);
    48
    49          } catch (IllegalAccessException e) {
    50              throw new RuntimeException(e);
    51
    52          } catch (InvocationTargetException e) {
    53              throw new RuntimeException(e);
    54          }
    55      }
    56  }