分享

org.springside.modules.utils.ReflectionUtils

 昵称15698534 2014-03-31
001import java.lang.reflect.Field;
002import java.lang.reflect.InvocationTargetException;
003import java.lang.reflect.Method;
004import java.lang.reflect.Modifier;
005import java.lang.reflect.ParameterizedType;
006import java.lang.reflect.Type;
007import java.util.ArrayList;
008import java.util.Collection;
009import java.util.Date;
010import java.util.List;
011 
012import org.apache.commons.beanutils.ConvertUtils;
013import org.apache.commons.beanutils.PropertyUtils;
014import org.apache.commons.beanutils.converters.DateConverter;
015import org.apache.commons.lang.StringUtils;
016import org.slf4j.Logger;
017import org.slf4j.LoggerFactory;
018import org.springframework.util.Assert;
019 
020/**
021 * 反射工具类.
022 *
023 * 提供访问私有变量,获取泛型类型Class, 提取集合中元素的属性, 转换字符串到对象等Util函数.
024 *
025 */
026public class ReflectionUtils {
027 
028    private static Logger logger = LoggerFactory.getLogger(ReflectionUtils.class);
029 
030    static {
031        DateConverter dc = new DateConverter();
032        dc.setUseLocaleFormat(true);
033        dc.setPatterns(new String[] { "yyyy-MM-dd""yyyy-MM-dd HH:mm:ss" });
034        ConvertUtils.register(dc, Date.class);
035    }
036 
037    /**
038     * 调用Getter方法.
039     */
040    public static Object invokeGetterMethod(Object target, String propertyName) {
041        String getterMethodName = "get" + StringUtils.capitalize(propertyName);
042        return invokeMethod(target, getterMethodName, new Class[] {}, new Object[] {});
043    }
044 
045    /**
046     * 调用Setter方法.使用value的Class来查找Setter方法.
047     */
048    public static void invokeSetterMethod(Object target, String propertyName, Object value) {
049        invokeSetterMethod(target, propertyName, value, null);
050    }
051 
052    /**
053     * 调用Setter方法.
054     *
055     * @param propertyType 用于查找Setter方法,为空时使用value的Class替代.
056     */
057    public static void invokeSetterMethod(Object target, String propertyName, Object value, Class<?> propertyType) {
058        Class<?> type = propertyType != null ? propertyType : value.getClass();
059        String setterMethodName = "set" + StringUtils.capitalize(propertyName);
060        invokeMethod(target, setterMethodName, new Class[] { type }, new Object[] { value });
061    }
062 
063    /**
064     * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数.
065     */
066    public static Object getFieldValue(final Object object, final String fieldName) {
067        Field field = getDeclaredField(object, fieldName);
068 
069        if (field == null) {
070            throw new IllegalArgumentException("Could not find field [" + fieldName +"] on target [" + object + "]");
071        }
072 
073        makeAccessible(field);
074 
075        Object result = null;
076        try {
077            result = field.get(object);
078        catch (IllegalAccessException e) {
079            logger.error("不可能抛出的异常{}", e.getMessage());
080        }
081        return result;
082    }
083 
084    /**
085     * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
086     */
087    public static void setFieldValue(final Object object, final String fieldName, finalObject value) {
088        Field field = getDeclaredField(object, fieldName);
089 
090        if (field == null) {
091            throw new IllegalArgumentException("Could not find field [" + fieldName +"] on target [" + object + "]");
092        }
093 
094        makeAccessible(field);
095 
096        try {
097            field.set(object, value);
098        catch (IllegalAccessException e) {
099            logger.error("不可能抛出的异常:{}", e.getMessage());
100        }
101    }
102 
103    /**
104     * 直接调用对象方法, 无视private/protected修饰符.
105     */
106    public static Object invokeMethod(final Object object, final String methodName,final Class<?>[] parameterTypes,
107            final Object[] parameters) {
108        Method method = getDeclaredMethod(object, methodName, parameterTypes);
109        if (method == null) {
110            throw new IllegalArgumentException("Could not find method [" + methodName +"] on target [" + object + "]");
111        }
112 
113        method.setAccessible(true);
114 
115        try {
116            return method.invoke(object, parameters);
117        catch (Exception e) {
118            throw convertReflectionExceptionToUnchecked(e);
119        }
120    }
121 
122    /**
123     * 循环向上转型, 获取对象的DeclaredField.
124     *
125     * 如向上转型到Object仍无法找到, 返回null.
126     */
127    protected static Field getDeclaredField(final Object object, final String fieldName) {
128        Assert.notNull(object, "object不能为空");
129        Assert.hasText(fieldName, "fieldName");
130        for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass
131                .getSuperclass()) {
132            try {
133                return superClass.getDeclaredField(fieldName);
134            catch (NoSuchFieldException e) {//NOSONAR
135                // Field不在当前类定义,继续向上转型
136            }
137        }
138        return null;
139    }
140 
141    /**
142     * 强行设置Field可访问.
143     */
144    protected static void makeAccessible(final Field field) {
145        if (!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) {
146            field.setAccessible(true);
147        }
148    }
149 
150    /**
151     * 循环向上转型, 获取对象的DeclaredMethod.
152     *
153     * 如向上转型到Object仍无法找到, 返回null.
154     */
155    protected static Method getDeclaredMethod(Object object, String methodName, Class<?>[] parameterTypes) {
156        Assert.notNull(object, "object不能为空");
157 
158        for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass
159                .getSuperclass()) {
160            try {
161                return superClass.getDeclaredMethod(methodName, parameterTypes);
162            catch (NoSuchMethodException e) {//NOSONAR
163                // Method不在当前类定义,继续向上转型
164            }
165        }
166        return null;
167    }
168 
169    /**
170     * 通过反射, 获得Class定义中声明的父类的泛型参数的类型.
171     * 如无法找到, 返回Object.class.
172     * eg.
173     * public UserDao extends HibernateDao<User>
174     *
175     * @param clazz The class to introspect
176     * @return the first generic declaration, or Object.class if cannot be determined
177     */
178    @SuppressWarnings("unchecked")
179    public static <T> Class<T> getSuperClassGenricType(final Class clazz) {
180        return getSuperClassGenricType(clazz, 0);
181    }
182 
183    /**
184     * 通过反射, 获得定义Class时声明的父类的泛型参数的类型.
185     * 如无法找到, 返回Object.class.
186     *
187     * 如public UserDao extends HibernateDao<User,Long>
188     *
189     * @param clazz clazz The class to introspect
190     * @param index the Index of the generic ddeclaration,start from 0.
191     * @return the index generic declaration, or Object.class if cannot be determined
192     */
193    @SuppressWarnings("unchecked")
194    public static Class getSuperClassGenricType(final Class clazz, final int index) {
195        Type genType = clazz.getGenericSuperclass();
196 
197        if (!(genType instanceof ParameterizedType)) {
198            logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
199            return Object.class;
200        }
201 
202        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
203 
204        if (index >= params.length || index < 0) {
205            logger.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
206                    + params.length);
207            return Object.class;
208        }
209        if (!(params[index] instanceof Class)) {
210            logger.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
211            return Object.class;
212        }
213 
214        return (Class) params[index];
215    }
216 
217    /**
218     * 提取集合中的对象的属性(通过getter函数), 组合成List.
219     *
220     * @param collection 来源集合.
221     * @param propertyName 要提取的属性名.
222     */
223    @SuppressWarnings("unchecked")
224    public static List convertElementPropertyToList(final Collection collection, finalString propertyName) {
225        List list = new ArrayList();
226 
227        try {
228            for (Object obj : collection) {
229                list.add(PropertyUtils.getProperty(obj, propertyName));
230            }
231        catch (Exception e) {
232            throw convertReflectionExceptionToUnchecked(e);
233        }
234 
235        return list;
236    }
237 
238    /**
239     * 提取集合中的对象的属性(通过getter函数), 组合成由分割符分隔的字符串.
240     *
241     * @param collection 来源集合.
242     * @param propertyName 要提取的属性名.
243     * @param separator 分隔符.
244     */
245    @SuppressWarnings("unchecked")
246    public static String convertElementPropertyToString(final Collection collection,final String propertyName,
247            final String separator) {
248        List list = convertElementPropertyToList(collection, propertyName);
249        return StringUtils.join(list, separator);
250    }
251 
252    /**
253     * 转换字符串到相应类型.
254     *
255     * @param value 待转换的字符串
256     * @param toType 转换目标类型
257     */
258    @SuppressWarnings("unchecked")
259    public static <T> T convertStringToObject(String value, Class<T> toType) {
260        try {
261            return (T) ConvertUtils.convert(value, toType);
262        catch (Exception e) {
263            throw convertReflectionExceptionToUnchecked(e);
264        }
265    }
266 
267    /**
268     * 将反射时的checked exception转换为unchecked exception.
269     */
270    public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) {
271        return convertReflectionExceptionToUnchecked(null, e);
272    }
273 
274    public static RuntimeException convertReflectionExceptionToUnchecked(String desc, Exception e) {
275        desc = (desc == null) ? "Unexpected Checked Exception." : desc;
276        if (e instanceof IllegalAccessException || e instanceofIllegalArgumentException
277                || e instanceof NoSuchMethodException) {
278            return new IllegalArgumentException(desc, e);
279        else if (e instanceof InvocationTargetException) {
280            return new RuntimeException(desc, ((InvocationTargetException) e).getTargetException());
281        else if (e instanceof RuntimeException) {
282            return (RuntimeException) e;
283        }
284        return new RuntimeException(desc, e);
285    }
286 
287    public static final <T> T getNewInstance(Class<T> cls) {
288        try {
289            return cls.newInstance();
290        catch (InstantiationException e) {
291            e.printStackTrace();
292        catch (IllegalAccessException e) {
293            e.printStackTrace();
294        }
295        return null;
296    }
297}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多