您的位置:首页 > 编程语言 > Java开发

将java集合转换成map

2015-12-16 00:00 337 查看
摘要: 将java集合转换成map

public class ReflectionUtil {
private static Logger logger = LoggerFactory.getLogger(ReflectionUtil.class);

public static Object invokeGetterMethod(Object obj, String propertyName) {
String getterMethodName = "get" + StringUtil.capitalize(propertyName);
return invokeMethod(obj, getterMethodName, new Class[0], new Object[0]);
}

public static void invokeSetterMethod(Object obj, String propertyName, Object value) {
invokeSetterMethod(obj, propertyName, value, null);
}

public static void invokeSetterMethod(Object obj, String propertyName, Object value, Class<?> propertyType) {
Class type = propertyType != null ? propertyType : value.getClass();
String setterMethodName = "set" + StringUtil.capitalize(propertyName);
invokeMethod(obj, setterMethodName, new Class[] { type }, new Object[] { value });
}

public static Object getFieldValue(Object obj, 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;
}

public static void setFieldValue(Object obj, String fieldName, 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());
}
}

public static Field getAccessibleField(Object obj, String 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) {
}
return null;
}

public static Object invokeMethod(Object obj, String methodName, Class<?>[] parameterTypes, 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);
}

}

public static Object invokeStaticMethod(Class<?> cls, String methodName, Class<?>[] parameterTypes, Object... args) {
try {
Method method = cls.getDeclaredMethod(methodName, parameterTypes);
if (method == null) {
throw new IllegalArgumentException("Could not find method [" + methodName + "] on class name [" + cls.getName() + "]");
}
return method.invoke(null, args);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return null;
}

public static Object invokeStaticMethodByFullMethodName(String fullMethodName, Object... args) throws ClassNotFoundException{
int index = fullMethodName.lastIndexOf(".");
String className = fullMethodName.substring(0, index);
String methodName = fullMethodName.substring(index + 1);
Class<?> clazz = Class.forName(className);
Class<?>[] parameterTypes = null;
if(args != null){
parameterTypes = new Class[args.length];
for(int i=0; i<args.length; i++){
parameterTypes[i] = args[i].getClass();
}
}
return ReflectionUtil.invokeStaticMethod(clazz, methodName, parameterTypes, args).toString();
}

public static Method getAccessibleMethod(Object obj, String methodName, Class<?>[] parameterTypes) {
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) {
}
}
return null;
}

public static Class getSuperClassGenricType(Class clazz) {
return getSuperClassGenricType(clazz, 0);
}

public static Class getSuperClassGenricType(Class clazz, 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];
}

public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) {
if (((e instanceof IllegalAccessException)) || ((e instanceof IllegalArgumentException)) || ((e instanceof NoSuchMethodException))) {
return new IllegalArgumentException("Reflection Exception.", e);
}
if ((e instanceof InvocationTargetException))
return new RuntimeException("Reflection Exception.", ((InvocationTargetException) e).getTargetException());
if ((e instanceof RuntimeException)) {
return (RuntimeException) e;
}
return new RuntimeException("Unexpected Checked Exception.", e);
}

public static List<Field> getFieldList(Class<?> cls, boolean isContainSupper) {
List<Field> fieldList = new ArrayList<Field>();
Field[] fields = null;
while (cls != null) {
fields = cls.getDeclaredFields();
for (Field field : fields) {
if (Modifier.isPrivate(field.getModifiers()) && !Modifier.isFinal(field.getModifiers()) && !Modifier.isStatic(field.getModifiers())) {
fieldList.add(field);
}
}
if (!isContainSupper) {
break;
}
cls = cls.getSuperclass();
}
return fieldList;
}
/**
* 将集合转换成map
* @param data
* @param keyProperty 作为map key的属性名称
* @param clazz 作为map key的类型
* @return
*/
public static<K, V> Map<K,V> CollectionToMap(Collection<V> data, String keyProperty, Class<K> clazz){
Map<K, V> dataMap = new HashMap<K, V>();
K key = null;
for(V obj : data){
key = clazz.cast(getFieldValue(obj, keyProperty));
dataMap.put(key, obj);
}
return dataMap;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: