zoukankan      html  css  js  c++  java
  • 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()));
                    }
                }
            }
        }
  • 相关阅读:
    [自创]mootools所有复选框只能选择一个的功能
    tomcat设置https访问
    更改tomcat运行时标题
    Java日期操作: 查找星期一和星期天
    mysql 常用数据查询
    git pull代码冲突
    antd model form数据不刷新问题
    前端开发常见面试题
    whistle 使用步骤
    windows 环境 启动报错 '.inconfig' 不是内部或外部命令,也不是可运行的程序
  • 原文地址:https://www.cnblogs.com/bigwolf/p/4819700.html
Copyright © 2011-2022 走看看