Java object in the attribute value is an empty string to null

Business logic required to convert the object attribute empty string is null, a simple way is distal JS control, not the empty string if the transmitted background, the background is not received by the attribute value default to null. This approach will lead to JS cumbersome. The following back- to resolve this issue by way of reflection.

    public static <T> T setNullValue(T source) throws IllegalArgumentException, IllegalAccessException, SecurityException {
        Field[] fields = source.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.getGenericType().toString().equals(
                    "class java.lang.String")) {
                field.setAccessible(true); 
                Object obj = field.get(source);
                if (obj != null && obj.equals("")) {
                    field.set(source, null);
                } else if (obj != null) {
                    String str = obj.toString();
                    str = StringEscapeUtils.escapeSql(str);//StringEscapeUtils是commons-lang中的通用类
                    field.set(source, str.replace("\\", "\\" + "\\").replace("(", "\\(").replace(")", "\\)")
                            .replace("%", "\\%").replace("*", "\\*").replace("[", "\\[").replace("]", "\\]")
                            .replace("|", "\\|").replace(".", "\\.").replace("$", "\\$").replace("+", "\\+").trim()
                    );
                }
            }
        }
        return source;
    }

Only you need to call it in the above methods to pre-treatment business.

Published 46 original articles · won praise 13 · views 60000 +

Guess you like

Origin blog.csdn.net/luliuliu1234/article/details/80947001