項目中使用的,拿去就可以用.
package com.qsqx.utils;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import org.apache.commons.collections.CollectionUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
/**
* 集合轉換
*
*
*/
public class CollectionTrans {
@SuppressWarnings("unchecked")
public static <T, K> List<K> extractListField(Collection<T> list, String fieldName) {
List<K> rs = Lists.newArrayList();
for (T t : list) {
K v = (K) ReflectionUtils.getFieldValue(t, fieldName);
rs.add(v);
}
return rs;
}
public static <T, K> List<K> extractListField(Collection<T> list, Function<T, K> fun) {
List<K> rs = Lists.newArrayList();
for (T t : list) {
K v = fun.apply(t);
rs.add(v);
}
return rs;
}
/**
* 去除重複數據
*
* @return
*/
@SuppressWarnings("unchecked")
public static <T, K> Map<K, T> list2Map(Collection<T> list, String fieldName) {
if (CollectionUtils.isEmpty(list)) {
return Collections.EMPTY_MAP;
}
Map<K, T> map = Maps.newHashMap();
for (T t : list) {
K key = (K) ReflectionUtils.getFieldValue(t, fieldName);
if (key != null) {
map.put(key, t);
}
}
return map;
}
public static <T> List<T> String2List(String str, Function<String, T> fun) {
return String2List(str, ",", fun);
}
public static <T> List<T> String2List(String str, String regex, Function<String, T> fun) {
String[] transArr = str.split(regex);
List<String> list = Lists.newArrayList(transArr);
List<T> rs = extractListField(list, fun);
return rs;
}
}
package com.qsqx.utils;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
/**
* 反射工具類.
*
* 提供訪問私有變量,獲取泛型類型Class, 提取集合中元素的屬性, 轉換字符串到對象等Util函數.
*
*/
public class ReflectionUtils {
private static Logger logger = LoggerFactory.getLogger(ReflectionUtils.class);
/**
* 調用Getter方法.
*/
public static Object invokeGetterMethod(Object obj, String propertyName) {
String getterMethodName = "get" + StringUtils.capitalize(propertyName);
return invokeMethod(obj, getterMethodName, new Class[] {}, new Object[] {});
}
/**
* 調用Setter方法.使用value的Class來查找Setter方法.
*/
public static void invokeSetterMethod(Object obj, String propertyName, Object value) {
invokeSetterMethod(obj, propertyName, value, null);
}
/**
* 調用Setter方法.
*
* @param propertyType 用於查找Setter方法,爲空時使用value的Class替代.
*/
public static void invokeSetterMethod(Object obj, String propertyName, Object value, Class<?> propertyType) {
Class<?> type = propertyType != null ? propertyType : value.getClass();
String setterMethodName = "set" + StringUtils.capitalize(propertyName);
invokeMethod(obj, setterMethodName, new Class[] { type }, new Object[] { value });
}
/**
* 直接讀取對象屬性值, 無視private/protected修飾符, 不經過getter函數.
*/
public static Object getFieldValue(final Object obj, final String fieldName) {
Field field = getAccessibleField(obj, fieldName);
if (field == null) {
throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
}
Object result = null;
try {
result = field.get(obj);
} catch (IllegalAccessException e) {
logger.error("不可能拋出的異常{}", e.getMessage());
}
return result;
}
/**
* 直接設置對象屬性值, 無視private/protected修飾符, 不經過setter函數.
*/
public static void setFieldValue(final Object obj, final String fieldName, final Object value) {
Field field = getAccessibleField(obj, fieldName);
if (field == null) {
throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
}
try {
field.set(obj, value);
} catch (IllegalAccessException e) {
logger.error("不可能拋出的異常:{}", e.getMessage());
}
}
/**
* 循環向上轉型, 獲取對象的DeclaredField, 並強制設置爲可訪問.
*
* 如向上轉型到Object仍無法找到, 返回null.
*/
public static Field getAccessibleField(final Object obj, final String fieldName) {
Assert.notNull(obj, "object不能爲空");
Assert.hasText(fieldName, "fieldName");
for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
try {
Field field = superClass.getDeclaredField(fieldName);
field.setAccessible(true);
return field;
} catch (NoSuchFieldException e) {//NOSONAR
// Field不在當前類定義,繼續向上轉型
}
}
return null;
}
/**
* 直接調用對象方法, 無視private/protected修飾符.
* 用於一次性調用的情況.
*/
public static Object invokeMethod(final Object obj, final String methodName, final Class<?>[] parameterTypes,
final Object[] args) {
Method method = getAccessibleMethod(obj, methodName, parameterTypes);
if (method == null) {
throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]");
}
try {
return method.invoke(obj, args);
} catch (Exception e) {
throw convertReflectionExceptionToUnchecked(e);
}
}
/**
* 循環向上轉型, 獲取對象的DeclaredMethod,並強制設置爲可訪問.
* 如向上轉型到Object仍無法找到, 返回null.
*
* 用於方法需要被多次調用的情況. 先使用本函數先取得Method,然後調用Method.invoke(Object obj, Object... args)
*/
public static Method getAccessibleMethod(final Object obj, final String methodName,
final Class<?>... parameterTypes) {
Assert.notNull(obj, "object不能爲空");
for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
try {
Method method = superClass.getDeclaredMethod(methodName, parameterTypes);
method.setAccessible(true);
return method;
} catch (NoSuchMethodException e) {//NOSONAR
// Method不在當前類定義,繼續向上轉型
}
}
return null;
}
/**
* 通過反射, 獲得Class定義中聲明的父類的泛型參數的類型.
* 如無法找到, 返回Object.class.
* eg.
* public UserDao extends HibernateDao<User>
*
* @param clazz The class to introspect
* @return the first generic declaration, or Object.class if cannot be determined
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> Class<T> getSuperClassGenricType(final Class clazz) {
return getSuperClassGenricType(clazz, 0);
}
/**
* 通過反射, 獲得Class定義中聲明的父類的泛型參數的類型.
* 如無法找到, 返回Object.class.
*
* 如public UserDao extends HibernateDao<User,Long>
*
* @param clazz clazz The class to introspect
* @param index the Index of the generic ddeclaration,start from 0.
* @return the index generic declaration, or Object.class if cannot be determined
*/
@SuppressWarnings("rawtypes")
public static Class getSuperClassGenricType(final Class clazz, final int index) {
Type genType = clazz.getGenericSuperclass();
if (!(genType instanceof ParameterizedType)) {
logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
return Object.class;
}
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) {
logger.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
+ params.length);
return Object.class;
}
if (!(params[index] instanceof Class)) {
logger.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
return Object.class;
}
return (Class) params[index];
}
/**
* 將反射時的checked exception轉換爲unchecked exception.
*/
public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) {
if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException
|| e instanceof NoSuchMethodException) {
return new IllegalArgumentException("Reflection Exception.", e);
} else if (e instanceof InvocationTargetException) {
return new RuntimeException("Reflection Exception.", ((InvocationTargetException) e).getTargetException());
} else if (e instanceof RuntimeException) {
return (RuntimeException) e;
}
return new RuntimeException("Unexpected Checked Exception.", e);
}
}