一、前言
关于通过java.lang.reflect.Field/java.lang.reflect.Method反射属性方法实现ReflectUtils工具类,实现了基于class创建实例createInstance方法、属性Field类对象实例获取属性值、类对象实例指定property属性字符串获取值invokeGetter、类对象实例指定方法反射调用invokeMethod、给类属性setter值进行反射调用赋值setField等操作。
二、代码示例
import java.lang.reflect.Field;@b@import java.lang.reflect.Method;@b@import java.util.Arrays;@b@@b@public class ReflectUtils@b@{@b@ public static <T> T createInstance(Class<?> clazz)@b@ {@b@ try@b@ {@b@ if (clazz == null)@b@ return null;@b@@b@ return clazz.newInstance();@b@ }@b@ catch (Exception e) {@b@ throw new RuntimeException("Error occured during creating instance of " + clazz, e);@b@ }@b@ }@b@@b@ public static Object getField(Field field, Object instance) throws RuntimeException {@b@ try {@b@ if (!(field.isAccessible())) {@b@ field.setAccessible(true);@b@ }@b@@b@ return field.get(instance);@b@ } catch (Exception e) {@b@ throw new RuntimeException("Error occured during getting field: " + field, e.getCause());@b@ }@b@ }@b@@b@ public static Object invokeGetter(Object instance, String property) {@b@ Method getter;@b@ Class clazz = instance.getClass();@b@ try@b@ {@b@ getter = clazz.getMethod("get" + Character.toUpperCase(property.charAt(0)) + property.substring(1), new Class[0]);@b@ } catch (Exception e) {@b@ throw new RuntimeException("No getter method found: " + e, e);@b@ }@b@@b@ return invokeMethod(getter, instance, new Object[0]);@b@ }@b@@b@ public static Object invokeMethod(Method method, Object instance, Object[] parameters) throws RuntimeException {@b@ try {@b@ return method.invoke(instance, parameters);@b@ }@b@ catch (Exception e) {@b@ throw new RuntimeException("Error occured during invoking method: " + method + " with parameters(" + @b@ Arrays.asList(parameters)@b@ + ")", e.getCause());@b@ }@b@ }@b@@b@ public static void setField(Field field, Object instance, Object value) throws RuntimeException {@b@ try {@b@ if (!(field.isAccessible())) {@b@ field.setAccessible(true);@b@ }@b@@b@ field.set(instance, value);@b@ }@b@ catch (Exception e) {@b@ throw new RuntimeException("Error occured during setting field: " + field + " with value(" + value + ")", e@b@ .getCause());@b@ }@b@ }@b@}