Java 属性转换工具

JAVA实体类对象属性转换工具

  • 当属性为null时转换成” “

    public static  void converEmptyNullToString(Object object) {
    
            try {
                //利用反射获取类的所有属性
                Field[] fs = object.getClass().getDeclaredFields();
                for (int i = 0; i < fs.length; i++) {
                    Field f = fs[i];
                    //设置属性可以访问
                    f.setAccessible(true);
                    Object val = f.get(object);
                    //得到此属性的类型
                    String type = f.getType().toString();
                    if (type.endsWith("String")) {
                        if (""!= val && null == val) {
                            f.set(object, "");
                        }
                    }
                }
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
    
        }
    
posted @ 2021-09-21 16:34  ynsocool  阅读(114)  评论(0)    收藏  举报