java 泛型方法

  有时候一个静态方法需要用泛型支撑,这个时候这个静态方法必须修改为泛型方法。即在返回值前面加一个<T>.

  对于一个静态方法而言,无法访问泛型类的类型参数,所以,如果static方法需要使用泛型能力,就必须使其成为泛型方法。

  

/**
     * Document转化为class
     *
     * @Title: getObject
     * @param doc
     * @param cls
     * @return
     * @author lihui
     * @param <T>
     * @throws Exception
     * @throws SecurityException
     * @throws NoSuchMethodException
     * @date 2015年9月18日 下午1:18:29
     */
    public static <T> void getObject(Document doc, T cls) throws NoSuchMethodException, SecurityException, Exception {
        Field fd[] = cls.getClass().getDeclaredFields();
        Object object = cls;
        for (Field field : fd) {
            System.out.println(field.getGenericType().toString());
            Object value = doc.get(field.getName());
            if (value != null && !value.toString().equals("")) {
                PropertyDescriptor pd = new PropertyDescriptor(field.getName(), cls.getClass());
                Method m = pd.getWriteMethod();// 获得写方法
                if (field.getGenericType().toString().equals("class java.lang.String")) {
                    m.invoke(object, value.toString());
                }

                else if (field.getGenericType().toString().equals("class java.lang.Integer")) {
                    m.invoke(object, Integer.valueOf(value.toString()));
                }

                else if (field.getGenericType().toString().equals("class java.lang.Double")) {
                    m.invoke(object, Double.valueOf(value.toString()));
                }

                else if (field.getGenericType().toString().equals("class java.lang.Long")) {
                    m.invoke(object, Long.valueOf(value.toString()));
                }

                else if (field.getGenericType().toString().equals("class java.lang.Boolean")) {
                    m.invoke(object, Boolean.valueOf(value.toString()));
                }

                else if (field.getGenericType().toString().equals("class java.util.Date")) {
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    m.invoke(object, df.parse(value.toString()));
                }
            }
        }
    }
原文地址:https://www.cnblogs.com/bigwolf/p/4819700.html