java泛型实例化

  • 2018-06-20
  • 浏览 (1286)

java的泛型怎样生成实例对象呢?按照以往的经验,我们很容易这样实现:
public static <T> T create(T t) {
    t = new T();
    return t;
}

此时,由于T的具体类型我们无法获得,所以new T()是无法通过编译的。换一种思路,我们不妨使用反射机制,通过T的Class对象的newInstance()方法来获取它的实例,生成T对象的代码如下所示:
public static <T> T create(Class<T> clazz) {
    T t = null;
    try {
        t = clazz.newInstance();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return t;
}

下面是将一个T类的list转换成E类的list,将T类实例里的相应属性copy到E类实例的工具类:
public class BeanUtil {
    public static <T, E> List<E> copyListProperties(List<T> source, Class<E> clazz) {
        List<E> es = new ArrayList<>();
        if (source != null && source.size() > 0) {
            for (T object : source) {
                E target = create(clazz);
                BeanUtils.copyProperties(object, target);
                es.add(target);
            }
        }
        return es;
    }

    public static <T, E> E copyProperties(T source, Class<E> clazz) {
        E target = create(clazz);
        if (source != null) {
            BeanUtils.copyProperties(source, target);
        }
        return target;
    }

    public static <T> T create(Class<T> clazz) {
        T t = null;
        try {
            t = clazz.newInstance();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return t;
    }
}

0  赞