How to remove spaces in objects in JAVA
JAVA in how to remove the space in the object, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.
Use the JAVA reflection mechanism to remove spaces from string attributes in an object.
Note: if the attribute itself is a "", it will also be replaced. If you need to filter, just append the judgment after objectfiltering null.
Public static void objectToTrim (Object obj) throws IllegalAccessException {Map map = new HashMap (); Field [] declaredFields = obj.getClass (). GetDeclaredFields (); for (Field field:declaredFields) {String type = field.getType (). GetCanonicalName (); if (StringUtils.equals (java.lang.String), type) {field.setAccessible (true); Object object = field.get (obj) If (object! = null) {String trim = object.toString () .replace ("", "); map.put (field.getName (), trim) } for (Field field:declaredFields) {if (map.get (field.getName ())! = null) {String s = map.get (field.getName ()); field.setAccessible (true); field.set (obj,s) }} public static void main (String [] args) throws IllegalAccessException {IdCode idCode = new IdCode (); idCode.setDeleteFlag (1); idCode.setCreateDate (LocalDateTime.now ()); idCode.setDeptId (""); idCode.setEducationUrl ("abvc"); idCode.setIdCode ("b c ddd"); System.out.println (idCode.toString ()) System.out.println ("= removed spaces ="); objectToTrim (idCode); System.out.println (idCode.toString ());}
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.