工具类代码:
package vip.rory.dht.common.util;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
/**
* @author zhanghangtian
*/
public class BeanUtil {
@SuppressWarnings("unchecked")
public static <T, K, V> T mapToBean(Map<K, V> map, TypeReference<T> typeReference)
throws IllegalArgumentException, InvocationTargetException, ClassNotFoundException, Exception {
Type type = typeReference.getRawType();
return (T) mapToBean(map, Class.forName(type.getTypeName()));
}
public static <T, K, V> T mapToBean(Map<K, V> map, Class<T> clazz)
throws Exception, IllegalArgumentException, InvocationTargetException {
T t = null;
try {
BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
t = clazz.newInstance();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
if (map.containsKey(key)) {
Object value = map.get(key);
Method setter = property.getWriteMethod();// Java中提供了用来访问某个属性的getter/setter方法
setter.invoke(t, value);
}
}
} catch (IntrospectionException e) {
e.printStackTrace();
}
return t;
}
public static Map<String, Object> beanToMap(Object bean) throws Exception, IllegalAccessException {
if (bean == null) {
return null;
}
Map<String, Object> map = new HashMap<String, Object>();
try {
BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
if (!key.equals("class")) {
Method getter = property.getReadMethod();// Java中提供了用来访问某个属性的 getter/setter方法
Object value;
value = getter.invoke(bean);
map.put(key, value);
}
}
} catch (IntrospectionException e) {
e.printStackTrace();
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
return map;
}
}
TypeReference代码:
package vip.rory.dht.common.util;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Represents a generic type {@code T}. Java doesn't yet provide a way to
* represent generic types, so this class does. Forces clients to create a
* subclass of this class which enables retrieval the type information even at
* runtime.
* <p>
* For example, to create a type literal for {@code List<String>}, you can
* create an empty anonymous inner class:
*
* <pre>
* TypeReference<List<String>> list = new TypeReference<List<String>>() {
* };
* </pre>
*
* This syntax cannot be used to create type literals that have wildcard
* parameters, such as {@code Class<?>} or {@code List<? extends CharSequence>}.
*/
public class TypeReference<T> {
static ConcurrentMap<Type, Type> classTypeCache = new ConcurrentHashMap<Type, Type>(16, 0.75f, 1);
protected final Type type;
protected final Type rawType;
/**
* Constructs a new type literal. Derives represented class from type
* parameter.
* <p>
* Clients create an empty anonymous subclass. Doing so embeds the type
* parameter in the anonymous class's type hierarchy so we can reconstitute
* it at runtime despite erasure.
*/
protected TypeReference() {
Type superClass = getClass().getGenericSuperclass();
Type type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
Type cachedType = classTypeCache.get(type);
if (cachedType == null) {
classTypeCache.putIfAbsent(type, type);
cachedType = classTypeCache.get(type);
}
this.rawType = ((ParameterizedType) type).getRawType();
this.type = cachedType;
}
/**
* Gets underlying {@code Type} instance.
*/
public Type getType() {
return type;
}
public Type getRawType() {
return rawType;
}
public final static Type LIST_STRING = new TypeReference<List<String>>() {
}.getType();
}
这篇博客介绍了如何使用Java工具类实现对象到Map、Map到对象以及Map到泛型对象的转换,重点是利用阿里巴巴的TypeReference解决泛型类型传递的问题。
553

被折叠的 条评论
为什么被折叠?



