General utility classes (strings, time formatting, BeanUtils, IO)
1. The Commons – lang3 library
1.1. Org.apache.com mons. Lang3. StringUtils class
In everyday code, we often work with strings and manipulate them. If we’re not careful, it’s easy to make a simple error like NullPointerException. We often write ifs to determine the non-business logic to handle these. At this point, we can use the wheel of Danox Apache, through some common methods in its StringUtils, improve our code, let our business code more concise, elegant. Sample code:
@Slf4j
public class AppTest {
@Test
public void stringUtils(){
String a = ""; String b = null; // Determine whether the character object is empty and whether the content is empty string (if there are Spaces, it is not empty string) log.info("StringUtils.isEmpty(a): {}", StringUtils.isEmpty(a)); // Determine whether the character object is empty and whether the content is empty string (if there are Spaces, it will be considered empty string) log.info("StringUtils.isBlank(a): {}", StringUtils.isBlank(a)); Stringutils.trim (b) can be used to avoid log.info()"StringUtils.trim(d): {}", StringUtils.trim(b));
String num = "12.3"; Stringutils.trim (b) can be used to avoid log.info()"org.apache.commons.lang3.StringUtils.isNumericSpace(): {} isNumber: {}", num, StringUtils.isNumericSpace(b));
log.info("com.alibaba.druid.util.StringUtils.isNumber(): {} isNumber: {}", num, com.alibaba.druid.util.StringUtils.isNumber(num)); }}Copy the code
1.2 org.apache.com mons. Lang3. Time. DateFormatUtils/DateUtils
Time conversion utility class:
@Test
public void dateFormatUtils() throws Exception{
String pattern = "yyyy-MM-dd HH:mm:ss";
String timeStr = DateFormatUtils.format(new Date(), pattern);
long timestamp = DateUtils.parseDate(timeStr, pattern).getTime();
log.info("==> current time: {}", timeStr);
log.info("==> current time timestamp: {}", timestamp);
}Copy the code
conclusion
Stringutils. isNotEmpty(STR): Stringutils. isNotEmpty(STR): Stringutils. isNotEmpty(STR): Stringutils. isNotEmpty(STR): Stringutils. isNotEmpty
Stringutils. isBlank(STR)/ stringutils. isNotBlank(STR): Determines whether the character object is null or an empty string.
Dateformatutils. format(date, pattern): Converts a date time object to a time string in the format of an expression
Dateutils. parseDate(timeStr, pattern): Inverts a time string into a Date object
ToStringBuilder. ReflectionToString (obj) : the object content into a string output (the next section is used to)
.
For learning a tool class, we can through Intellij IDEA can be opened by this kind of source code, and then through the shortcut keys (MacOS: Command +7; Windows: Alt+7) Open the list of class methods (Structure), from the method name probably can see the specific methods that are suitable for their use.
The jar packages used in the above examples can be imported via Maven’s pom.xml file dependency:
Mons < dependency > < groupId > org.apache.com < / groupId > < artifactId > Commons - lang3 < / artifactId > < version > 3.8.1 < / version > </dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.9</version> </dependency>Copy the code
2. com mon – beanutils library
Map and JavaBean are two types that are often used in our daily business code. Sometimes for business reasons, when Map and JavaBean need to convert copy to each other, if you manually set/put, you will spit blood when there are too many fields. Here we recommend using BeanUtils to simplify our code
2.1.org.apache.commons.beanutils.BeanUtils class
@Test
public void beanUtils() throws InvocationTargetException, IllegalAccessException {
CompanyBean bean = new CompanyBean();
bean.setId(1);
bean.setName("China Mobile Guangzhou Branch");
bean.setAddress(Zhongshan Avenue, Tianhe District, Guangzhou city);
bean.setTel("020-10086000"); CompanyBean destObj = new CompanyBean(); Beanutils.copyproperties (destObj, bean); // Copy beanUtils.copyProperties (destObj, bean); // The ToStringBuilder class comes from the Commons-lang3 library: converts object content to string output, which is convenient for logging log.info("destObj from BeanUtils.copyProperties: {}", ToStringBuilder.reflectionToString(destObj));
Map<String, Object> map = new HashMap<>();
map.put("id", 2);
map.put("name"."China Unicom Guangzhou Branch");
map.put("address".2 Zhongshan Dadao, Tianhe District, Guangzhou);
map.put("tel"."020-10000110"); Populate (destObj, map); // Populate (destObj, map). log.info("destObj from BeanUtils.populate: {}", ToStringBuilder.reflectionToString(destObj)); // Copy the object, in contrast to the copyProperties() method, where the new object can be used without first instantiating the CompanyBeancloneBean = (CompanyBean)BeanUtils.cloneBean(destObj);
log.info("cloneBean from BeanUtils.cloneBean: {}", ToStringBuilder.reflectionToString(cloneBean)); // Convert JavaBean to Map Map newMap = beanutils.describe (cloneBean);
log.info("newMap from BeanUtils.describe: {}", new Gson().toJson(newMap));
}Copy the code
The following output is displayed:
The 2019-01-19 13:17:21. [main] INFO 064 com. Monbuilder. AppTest - destObj from BeanUtils. CopyProperties: Com.monbuilder.bean.Com panyBean @ 10683 d9d [id = 1, name = China mobile guangzhou branch, address = guangzhou tianhe district zhongshan road no. 1, tel = 020-10086000] in the 2019-01-19 s 13:17:21.070 [main] info.monbuilder.apptest - destObj from BeanUtils. Populate: Com.monbuilder.bean.Com panyBean @ 10683 d9d [id = 2, guangzhou branch name = China unicom, address = guangzhou tianhe zhongshan road no. 2, tel = 020-10000110] in the 2019-01-19 s 13:48:14.966 [main] info.monbuilder.apptest - newMap from BeanUtils. Describe: {"address":2 Zhongshan Dadao, Tianhe District, Guangzhou."name":"China Unicom Guangzhou Branch"."tel":"020-10000110"."id":"2"."class":"class com.monbuilder.bean.CompanyBean"}
Copy the code
conclusion
Beanutils.copyproperties (destObj, sourceObj): Copy of content between Javabeans
Beanutils.clonebean (obj): Copy object
Populate (destObj, sourceMap): Map converts to Javabeans
Beanutils.describe (bean): Convert Javabeans to maps
3. com mons – IO library
Org.apache.com mons. IO. IOUtils class
The IO utility class is very useful for converting streams to byte arrays, closing streams after processing, etc. There is a lot of processing logic to write, such as “if nullating” for close, but using IOUtil, Our processing code or very concise.
@Test
public void ioUtils() throws IOException {
InputStream io = this.getClass().getClassLoader().getResourceAsStream("README.md");
BufferedReader br = new BufferedReader(new InputStreamReader(io));
log.info("==> IOUtils.toString(br): {}", IOUtils.toString(br));
IOUtils.closeQuietly(br);
IOUtils.closeQuietly(io);
}Copy the code
[main] infocom.monBuilder.appTest - ==> Ioutils.toString (br): Toolkit - Demo, tool class library use exampleCopy the code
conclusion
IOUtils commonly used methods are:
Ioutils. closeQuietly(obj): Close flow, Socket, SocketServer, etc
Ioutils. copy(InputStream, Writer): copies input streams
Ioutils.write (byte[], OutputStream): Converts a byte array to a stream
Ioutils.tobytearray (InputStream): converts an InputStream to a byte array
Ioutils.toinputstream (String): Converts a String to an input stream
Ioutils.tostring (InputStream): converts the InputStream to a string
The above are all from the apache official class library, there are many more classes and methods to explore and use. In addition, I also introduced another very famous tool class library: Guava, from Google; The functionality is similar, and of course there are many extended uses, which are not covered in detail in this article.
< the dependency > < groupId > com. Google. Guava < / groupId > < artifactId > guava < / artifactId > < version > 23.2 jre < / version > </dependency>Copy the code
JSON utility class
In today’s world of REST apis, where front-end and back-end separation is standard and JSON serves as a bridge between the two, we must be dealing with each other a lot at work. In Java development, there are no shortage of JSON utility classes to choose from:
Fastjson alibaba, fast conversion, but not stable performance
Gson Google product, easy to use, lightweight
Jackson Spring features fast performance, fast conversion, flexible configuration, and stable performance in different scenarios
Jackson is recommended if you are using Spring Boot or Spring Cloud, and the json library built into your Web project is Jackson.
JavaBean/ JSON interchange utility classes:
package com.monbuilder.util; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import java.text.SimpleDateFormat; /*** * JSON conversion tool class * @author <a href="mailto:[email protected]">Builder34</a>
* @date 2018-11-01 11:14:26
* */
@Slf4j
public class JacksonUtil {
private static ObjectMapper objectMapper = new ObjectMapper();
static {
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
objectMapper.configure(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true);
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); / / set the input to ignore and Java object actually did not exist in the JSON string attributes objectMapper. Configure (DeserializationFeature FAIL_ON_UNKNOWN_PROPERTIES,false); / / set the attribute of the output value is null objectMapper. SetSerializationInclusion (JsonInclude. Include. NON_NULL); } /** * deserializes a JSON string into a Java object based on the specified Class (if an exception occurs during conversion, a NULL object is returned) ** @param JSON JSON string * @param objClass JavaObject Class * @returnPublic static <T> T toJavaObject(String json, Class<T> objClass) {try {public static <T> T toJavaObject(String json, Class<T> objClass) {return objectMapper.readValue(json, objClass);
} catch (Exception e) {
log.error("", e);
returnnull; }} /** * Serialize a Java object to a JSON string (return an empty object JSON string if an exception occurs during conversion"{}"* * @param obj Java object to be serialized to generate a JSON string * @returnJSON String */ public static String toJsonString(Object obj) {try {return objectMapper.writeValueAsString(obj);
} catch (Exception e) {
log.error("",e);
}
return "{}"; }}Copy the code
Using the above utility class as an example:
@Test
public void jsonUtils(){
CompanyBean bean = new CompanyBean();
bean.setId(1);
bean.setName("China Mobile Guangzhou Branch");
bean.setAddress(1 Zhongshan Dadao, Tianhe District, Guangzhou);
bean.setTel("020-10086000");
log.info("==> JacksonUtil.toJsonString(bean): {}", JacksonUtil.toJsonString(bean));
String json = JacksonUtil.toJsonString(bean);
log.info("==> JacksonUtil.toJavaObject: {}", ToStringBuilder.reflectionToString(JacksonUtil.toJavaObject(json, CompanyBean.class)));
}Copy the code
[main] info.monBuilder.appTest - ==> JacksonUtil. ToJsonString (bean): {"id": 1,"name":"China Mobile Guangzhou Branch"."address":1 Zhongshan Dadao, Tianhe District, Guangzhou."tel":"020-10086000"} 15:42:16. 2019-01-19 144 [main] INFO com. Monbuilder. AppTest - = = > JacksonUtil. ToJavaObject: Com.monbuilder.bean.Com panyBean @ 376 a0d86 [id = 1, name = China mobile guangzhou branch, address = guangzhou tianhe district zhongshan road no. 1, tel = 020-10086000]Copy the code
Involved in the sample code above, all can be obtained through open making address [https://github.com/Builder34/toolkit-demo], or click here to read the original, jump to the code base connection.
Finally, there are a lot of wheels, and of course we can duplicate wheels, but what we advocate is to use existing good wheels (tool classes) to develop cleaner, more elegant code with clearer business logic.
-END-
Scan the wechat public account to follow, exchange and learn from each other