Common utility class methods
Background: THERE are some problems with a string of code I wrote while cr code.
String xxx=remoteClient.xxxservice();
if(xxx.isEmpty()){
xxxx;
}
Copy the code
There are two main problems:
- When a remote method is called, a variety of exceptions cannot be determined. The method may fail due to network reasons or timeout, or the method may fail to catch the exception RpcException or ioException as a whole.
- Second, there are nPE problems with isEmpty() methods such as String classes where the default caller is not NULL. It is recommended to use utility classes for these operations rather than build your own wheels
Solution:
- Remote method invocations encapsulate an intermediate layer where exception catching is performed, with a degree of importance to the business (strong/weak dependency) as to whether an exception is thrown to the caller or returned to a uniform default value. If there is a business Exception, throw a business Exception in advance and use Exception in the outermost layer to take the bottom out.
- Use the stringutils.isblank () utility class to determine the internal implementation automatically determines the NULL problem. When using method class methods, consider the meaning and ease of understanding of the calling method.
Follow-up summary:
Some understanding of common utility classes is required, such as the use of Lists. Partition () to determine the number of pages to avoid your own code calculation. So it’s important to know some common tool classes. Common utility classes seen in projects are Commons, Utils, and Guava. List some common methods below.
Guava
Google Guava overview
Guava is a set of core Java libraries from Google, including new collection types (such as multimap and multiset), immutable collections, graphics libraries, and utilities for concurrency, I/O, hashing, caching, primitives, strings, and more! It is widely used in most Of Google’s Java projects and is widely used by many other companies.
2. Guava Github open Source: github.com/google/guav…
3. Official website user manual: github.com/google/guav…
4. Com.google. guava relies on:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>29.0-jre</version>
</dependency>
Copy the code
Immutable sets and objects
1. Making immutable copies of objects is a good defensive programming technique. Immutable objects have many advantages, including:
Available for secure use by untrusted libraries. Thread safety: Can be used by multiple threads without contention risk. Mutation support is not required, and time and space are saved, with all immutable collection implementations saving more memory than their mutable counterparts. Can be used as a constant with the expectation that it will stay the same.
2. Important: Every Implementation of Guava immutable collections rejects null values. Guava’s design recommends the use of null values, and in most cases an exception will be thrown when null values are encountered.
3. An ImmutableXxx collection can be created in one of the following ways:
Using the copyOf method, CopyOf (set) uses the of method, such as immutableset. of(“a”, “b”, “c”) or ImmutableMap. Of(“a”, 1, “b”, 2) uses the Builder method.
4. Guava provides easy-to-use immutable versions of each standard Java JDK collection type, including Guava’s own collection variants. The immutable versions provided for Java inherit the Java JDK interface, so the operation is basically the same. The implementation classes of the following interfaces also have immutable versions.
interface | The JDK or Guava | Immutable version |
---|---|---|
Collection |
JDK | ImmutableCollection |
List |
JDK | ImmutableList |
Set |
JDK | ImmutableSet |
SortedSet /NavigableSet |
JDK | ImmutableSortedSet |
Map |
JDK | ImmutableMap |
SortedMap |
JDK | ImmutableSortedMap |
Multiset |
Guava | ImmutableMultiset |
SortedMultiset |
Guava | ImmutableSortedMultiset |
Multimap |
Guava | ImmutableMultimap |
ListMultimap |
Guava | ImmutableListMultimap |
SetMultimap |
Guava | ImmutableSetMultimap |
BiMap |
Guava | ImmutableBiMap |
ClassToInstanceMap |
Guava | ImmutableClassToInstanceMap |
Table |
Guava | ImmutableTable |
Online demo source: github.com/main/java/c…
Official website: github.com/google/guav…
Guava new collection type
Guava introduces a number of new collection types that are not in the Java JDK but are very useful, all designed to coexist happily with the JDK collections framework rather than stuff into the JDK collection abstraction.
Multiset a repeatable collection
Guava provides a new collection type, Multiset, that supports adding multiple identical elements, where members can appear more than once.
2. A Multiset is equivalent to a Set, except that the same elements can be added to a Multiset. Inside a Multiset is maintained using a HashMap.
HashMultiset TreeMultiset HashMultiset TreeMultiset HashMultiset TreeMultiset LinkedHashMultiset is ordered and operates in exactly the same way as JDK HashSet, TreeSet, LinkedHashSet.
Online demo source: github.com/wangmaoxion…
Multimap Multiple mapping
1. Every experienced Java programmer has implemented Map<K, List> or Map<K, Set> somewhere, and Guava’s Multimap framework makes it easy to handle mappings from keys to multiple values, a generic way to associate keys with any number of values.
2. Conceptually, there are two ways to think of multiple mappings as a collection of mappings from a single key to a single value:
a -> 1 a -> [1.2.4]
a -> 2 b -> [3] way1 a -> 4way2 c -> [5]
b -> 3
c -> 5
Copy the code
3. Multimap provides multiple implementations:
Multimap implementation | Key uses | Value uses |
---|---|---|
ArrayListMultimap |
HashMap |
ArrayList |
HashMultimap |
HashMap |
HashSet |
LinkedListMultimap * |
LinkedHashMap``* |
LinkedList``* |
LinkedHashMultimap ** |
LinkedHashMap |
LinkedHashSet |
TreeMultimap |
TreeMap |
TreeSet |
ImmutableListMultimap |
ImmutableMap |
ImmutableList |
ImmutableSetMultimap |
ImmutableMap |
ImmutableSet |
4. Every implementation, with the exception of immutable implementations, supports empty keys and values. Not all implementations are implemented as a Map<K, Collection> (especially some Multimap implementations use custom hash tables to minimize overhead.)
Online demo source: github.com/wangmaoxion…
BiMap bidirectional mapping
1. The traditional way to map a value back to a key is to maintain two separate maps and keep them in sync, but this is error-prone and can be confusing when a value already exists in the map. Such as:
Map<String.Integer> nameToId = Maps.newHashMap();
Map<Integer.String> idToName = Maps.newHashMap();
nameToId.put("Bob".42);
idToName.put(42."Bob");
Copy the code
BiMap provides multiple implementations:
Key-value mapping implementation | Value key mapping implementation | Corresponding BiMap |
---|---|---|
HashMap |
HashMap |
HashBiMap |
ImmutableMap |
ImmutableMap |
ImmutableBiMap |
EnumMap |
EnumMap |
EnumBiMap |
EnumMap |
HashMap |
EnumHashBiMap |
Online demo source: github.com/wangmaoxion…
Table Table structure data
1. When you try to index multiple keys at once, you get code like Map<FirstName, Map<LastName, Person>>, which is ugly and awkward to use. Guava provides a new collection type, Table, that supports this use case for any “row” and “column” types.
2. Table provides multiple implementations:
HashBasedTable: Basically supported by HashMap
>. TreeBasedTable: Basically supported by TreeMap
>. ImmutableTableArrayTable: Requires that the full range of rows and columns be specified when constructed, but is supported by two-dimensional arrays for speed and memory efficiency when tables are dense. ArrayTable works a little differently than other implementations
Online demo source: github.com/wangmaoxion…
The ClassToInstanceMap type is mapped to the instance
1. Sometimes there is not a single type of key but multiple types. Guava provides ClassToInstanceMap for this, key can be multiple types and value is an instance of this type.
2, the implementation of ClassToInstanceMap: MutableClassToInstanceMap and ImmutableClassToInstanceMap implementation.
Online demo source: github.com/wangmaoxion…
JDK collection helper classes
1. Any programmer with experience with the JDK Collections framework will know and love the utility java.util.collections, which Guava provides with a number of static method utilities for Collections.
interface | JDK or Guava | Corresponding Guava API |
---|---|---|
Collection |
JDK | Collections2 |
List |
JDK | Lists |
Set |
JDK | Sets |
SortedSet |
JDK | Sets |
Map |
JDK | Maps |
SortedMap |
JDK | Maps |
Queue |
JDK | Queues |
Multiset |
Guava | Multisets |
Multimap |
Guava | Multimaps |
BiMap |
Guava | Maps |
Table |
Guava | Tables |
Lists online demo: github.com/wangmaoxion…
Sets online demo: github.com/wangmaoxion…
JDK base type helper classes
Guava provides utility classes for Java JDK primitives:
Basic types of | Guava assistive utility class |
---|---|
byte |
Bytes .SignedBytes .UnsignedBytes |
short |
Shorts |
int |
Ints .UnsignedInteger .UnsignedInts |
long |
Longs .UnsignedLong .UnsignedLongs |
float |
Floats |
double |
Doubles |
char |
Chars |
boolean |
Booleans |
Ints online demo source: github.com/wangmaoxion…
Doubles online demo source: github.com/src/main/ja…
Booleans online demo source: github.com/src/main/ja…
The same goes for other types.
JDK string helper classes
1. The Strings class provides a few commonly used string utilities. Online demo source code.
Iterable: java.util.Iterator: java.lang.Object[] : java.lang. Online demo source code.
3, Splitter is used to split character sequence java.lang.CharSequence, online demo source code.
CharMatcher character matcher, used to match characters, can be treated as representing a specific class of characters, such as numbers or whitespace. Note: CharMatcher only deals with char values. Online demo source code.
What kind of
Java 7 introduced the java.util.Objects class.
Just as Arrays is the utility class for Array, Collections is the utility class for Collection, and Objects is the utility class for Object, containing methods for manipulating Objects, most of which are null-pointer safe.
requireNonNull
methods
RequireNonNull was originally used for parameter validation in a method, defined as follows:
public static <T> T requireNonNull(T obj) {
if (obj == null)
throw new NullPointerException();
return obj;
}
public static <T> T requireNonNull(T obj, String message) {
if (obj == null)
throw new NullPointerException(message);
return obj;
}
public static <T> T requireNonNull(T obj, Supplier<String> messageSupplier) {
if (obj == null)
throw new NullPointerException(messageSupplier.get());
return obj;
}
Copy the code
null
judge
There are two methods for nullpointer determination that are semantically opposite:
isNull
nonNull
They are implemented as follows:
public static boolean isNull(Object obj) { return obj == null; } public static boolean nonNull(Object obj) { return obj ! = null; }Copy the code
IsNull and nonNull are predicates designed to be used as filters: filter(Objects::nonNull).
toString
methods
public static String toString(Object o) {
return String.valueOf(o);
}
Copy the code
ValueOf implements the following:
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
Copy the code
So objects. toString returns a NULL string for a null argument.
You can also specify the return value when the argument is null:
public static String toString(Object o, String nullDefault) { return (o ! = null) ? o.toString() : nullDefault; }Copy the code
equals
methods
public static boolean equals(Object a, Object b) { return (a == b) || (a ! = null && a.equals(b)); }Copy the code
- if
a
b
Are allnull
, it istrue
; If only one isnull
, it isfalse
The rest of the function
Objects has other functions, such as compare hash hashCode, which are not currently used.
This section describes common tool classes
The tools for each block below are sorted by how often I use them.
String handling
import org.apache.commons.lang3.StringUtils; boolean StringUtils.isBlank(str); // "" is true Boolean stringutils.isempty (STR); // "" for false Boolean stringutils. isNotBlank(STR); boolean StringUtils.isNotEmpty(str); String[] StringUtils.split(str,char/String,max); // Cut the string, using the given character; Max is primarily a String stringutils.capitalize (STR) that deals with empty content; // Capitalize String stringutils.uncapitalize (STR); // lowercase Boolean stringutils.isnumeric (STR); boolean StringUtils.isNumericSpace(str); / / "" true" 12 3 "to true String StringUtils. Join (array/Iterable, chat/String); LeftPad (STR,size,padChar); // Add a fixed length String stringutils. rightPad(STR,size,padChar); // Splice fixed length characters on the right sideCopy the code
Formatting information
import org.apache.commons.lang3.time.DateFormatUtils; import org.apache.commons.lang3.time.DurationFormatUtils; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; DateFormatUtils.format(Date/Calendar/long,pattern); DateFormatUtils.ISO_DATE_FORMAT.format(Date/Calendar/long); // yyyy-MM-dd DateFormatUtils.ISO_TIME_NO_T_FORMAT.format(Date/Calendar/long); // HH:mm:ss DurationFormatUtils.formatDuration(long,format); Param, Po,dto,vo @override Public String toString() {return ToStringBuilder.reflectionToString(this,ToStringStyle.SHORT_PREFIX_STYLE); }Copy the code
Collection and array handling
import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.collections.CollectionUtils; boolean ArrayUtils.isEmpty(Array); boolean ArrayUtils.isNotEmpty(Array); boolean CollectionUtils.isEmpty(Collection); boolean CollectionUtils.isNotEmpty(Collection); Collection CollectionUtils.union(a,b); / / and set Collection CollectionUtils. Intersection computes (a, b); / / intersection Collection CollectionUtils. Disjunction (a, b); // Subtract (a,b); / / difference setCopy the code
Date processing
import org.apache.commons.lang3.time.DateUtils; Date DateUtils.parseDate(str,parsePatterns); boolean DateUtils.isSameDay(Date,Date); Dateutils. truncate(Date,field); Date dateutils. round(Date,field); Truncate = 2019 truncate = 2019 truncate = 2019 But round gets 2020 Date dateutils.adddays (Date,amount); / / add a day, this will not modify the original date value And addYears addMonths addWeeks, addHours, addMinutes, addSeconds, addMilliseconds Date DateUtils.setDays(Date,amount); / / set for how many days this month and setYears setMonths, setHours, setMinutes, setSeconds, setMilliseconds / * calculation has been in the past days, where to start to calculate, according to the second parameter fragments to determine, . Now is the 2014-10-23 13:27:00, then DateUtils getFragmentInDays (new Date (), Calendar, the MONTH) return to 23, said 23 days have passed since that MONTH, DateUtils. GetFragmentInDays (new Date (), Calendar, YEAR) back to 296, said 296 days have passed since that YEAR, DateUtils. GetFragmentInHours (new Date (), Calendar, the Date) return to 13, Said from today has been for the past 13 hours * / long DateUtils. GetFragmentInDays (Date, fragments); // Count the days that have passedCopy the code
Some processing of numbers
import org.apache.commons.lang3.math.NumberUtils; int NumberUtils.toInt(String); And toLong toDouble toFloat, toShort such as Boolean NumberUtils. IsDigits (String); Boolean numberUtils. isNumber(String); // Class 0x expressions are supportedCopy the code
Enhanced reflection processing
import org.apache.commons.lang3.ClassUtils; import org.apache.commons.lang3.reflect.MethodUtils; import org.springframework.cglib.core.ReflectUtils; import org.springframework.util.ReflectionUtils; Class<? > ClassUtils.getClass(className); boolean ClassUtils.isInnerClass(Class<? >); . / / whether the inner Class Boolean ClassUtils isPrimitiveOrWrapper (Class <? >); / / it is a primitive type or the original type of wrapper Class List < Method > MethodUtils. GetMethodsListWithAnnotation (Class <? >, Class<? extends Annotation>); Method ReflectionUtils.findMethod(Class<? > clazz,methodName, Class<? >...). ; PropertyDescriptor[] ReflectUtils.getBeanGetters(Class type); Object MethodUtils.invokeMethod(object,methodName,args[],values[]); // Call the methodCopy the code
IO stream, file related methods
import org.apache.commons.io.IOUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; String IOUtils.toString(InputStream,encoding); List<String> ioutils. readLines(InputStream,encoding); List<String> int ioutils. copy(InputStream, OutputStream); void FileUtils.writeStringToFile(File, String, Charset); void FileUtils.deleteDirectory(File); String FilenameUtils.getBaseName(filename); / / get the file name String FilenameUtils. GetExtension (filename); / / to get extension String FilenameUtils. SeparatorsToUnix (String path); // Convert to the Linux path separatorCopy the code
Encryption and decryption correlation
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
byte[] Base64.encodeBase64(byte []);
byte[] Base64.decodeBase64(byte[]);
char [] Hex.encodeHex(byte []);
byte [] Hex.decodeHex(char []);
String DigestUtils.md5Hex(String);
String DigestUtils.shaHex(String);
Copy the code
Random number generation
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.RandomStringUtils;
int RandomUtils.nextInt(start,end);
long RandomUtils.nextLong(start,end);
String RandomStringUtils.randomNumeric(count);
String RandomStringUtils.randomAlphabetic(count);
Copy the code
Other tools available
/ / a StopWatch import org.apache.com mons. Lang3. Time. StopWatch; StopWatch stopWatch = new StopWatch(); stopWatch.start(); stopWatch.getTime(); stopWatch.stop(); / / spring acquisition method parameter name import org. Springframework. Core. ParameterNameDiscoverer; ParameterNameDiscoverer parameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer(); String[] parameterNames = parameterNameDiscoverer.getParameterNames(method); / / spring used for processing the comma separator string list methods import org. Springframework. Util. StringUtils; String [] StringUtils.tokenizeToStringArray(String str, String delimiters);Copy the code
Reference blog Reference blog Reference blog