Stop writing tool classes by yourself, Spring Boot has all the built-in tool classes you need! !

Assertion

  1. An assertion is a logical judgment that checks for something that shouldn’t happen

  2. The Assert keyword was introduced in JDK1.4 and can be turned on through the JVM parameter -enableassertions

  3. SpringBoot provides the Assert assertion tool class, which is usually used for data validity checking.

//Requires parameter object to be non-null (Not Null), otherwise an exception will be thrown and will not be released.
// Parameter message parameter is used to customize exception information.
void notNull(Object object, String message)
// It is required that the parameter must be empty (Null), otherwise an exception will be thrown and will not be "released".
// Contrary to the notNull() method assertion rules
void isNull(Object object, String message)
// The required parameter must be true (True), otherwise an exception will be thrown and will not be "released".
void isTrue(boolean expression, String message)
// It is required that the parameters (List/Set) must be non-empty (Not Empty), otherwise an exception will be thrown and will not be released.
void notEmpty(Collection collection, String message)
// It is required that the parameter (String) must have a length (ie, Not Empty), otherwise an exception will be thrown and will not be released.
void hasLength(String text, String message)
// It is required that the parameter (String) must have content (ie, Not Blank), otherwise an exception will be thrown and will not be released.
void hasText(String text, String message)
// The parameter is required to be an instance of the specified type, otherwise an exception will be thrown and will not be released.
void isInstanceOf(Class type, Object obj, String message)
// It is required that the parameter `subType` must be a subclass or implementation class of the parameter superType, otherwise an exception will be thrown and will not be released.
void isAssignable(Class superType, Class subType, String message)

Object, array, collection

ObjectUtils

  1. Get basic information about the object

//Get the class name of the object. When the parameter is null, the string returned: "null"
String nullSafeClassName(Object obj)
// When the parameter is null, return 0
int nullSafeHashCode(Object object)
// When the parameter is null, return string: "null"
String nullSafeToString(boolean[] array)
// Get the object HashCode (string in hexadecimal form). When the parameter is null, 0 is returned
String getIdentityHexString(Object obj)
// Get the class name and HashCode of the object. When the parameter is null, the string is returned: ""
String identityToString(Object obj)
// Equivalent to the toString() method, but when the parameter is null, the string is returned: ""
String getDisplayString(Object obj)
  1. judgment tool

// Determine whether the array is empty
boolean isEmpty(Object[] array)
// Determine whether the parameter object is an array
boolean isArray(Object obj)
// Determine whether the array contains the specified element
boolean containsElement(Object[] array, Object element)
// When equal, or both are null, return true
boolean nullSafeEquals(Object o1, Object o2)
/*
To determine whether the parameter object is empty, the judgment criteria are:
    Optional: Optional.empty()
       Array: length == 0
CharSequence: length == 0
  Collection: Collection.isEmpty()
         Map: Map.isEmpty()
 */
boolean isEmpty(Object obj)
  1. Other tool methods

//Append new elements to the end of the parameter array and return a new array
<A, O extends A> A[] addObjectToArray(A[] array, O obj)
// Native basic type array --> wrapper class array
Object[] toObjectArray(Object source)

StringUtils

Recommended address for fishing:

https://www.yoodb.com/slack-off/home.html

  1. String judgment tool

// Determine whether the string is null or "". Note that strings containing whitespace characters are non-empty
boolean isEmpty(Object str)
// Determine whether the string ends with the specified content. Ignore case
boolean endsWithIgnoreCase(String str, String suffix)
// Determine whether the string begins with the specified content. Ignore case
boolean startsWithIgnoreCase(String str, String prefix)
//Whether it contains whitespace characters
boolean containsWhitespace(String str)
// Determine if the string is not empty and the length is not 0, that is, Not Empty
boolean hasLength(CharSequence str)
// Determine whether the string contains actual content, that is, it does not only contain blank characters, that is, Not Blank
boolean hasText(CharSequence str)
// Determine whether the specified index of the string contains a substring.
boolean substringMatch(CharSequence str, int index, CharSequence substring)
// Count the number of occurrences of a specified substring in a string
int countOccurrencesOf(String str, String sub)
  1. String manipulation tools

//Find and replace the specified substring
String replace(String inString, String oldPattern, String newPattern)
//Remove specific characters at the end
String trimTrailingCharacter(String str, char trailingCharacter)
//Remove specific characters from the header
String trimLeadingCharacter(String str, char leadingCharacter)
//Remove leading whitespace characters
String trimLeadingWhitespace(String str)
//Remove leading whitespace characters
String trimTrailingWhitespace(String str)
//Remove leading and trailing whitespace characters
String trimWhitespace(String str)
// Remove leading, trailing and intermediate whitespace characters
String trimAllWhitespace(String str)
//Delete the specified substring
String delete(String inString, String pattern)
//Delete the specified character (can be multiple)
String deleteAny(String inString, String charsToDelete)
// Execute the trim() method on each item of the array
String[] trimArrayElements(String[] array)
//Decode the URL string
String uriDecode(String source, Charset charset)
  1. Path related tool methods

// Parse the path string and optimize the ".."
String cleanPath(String path)
// Parse the path string and parse out the file name part
String getFilename(String path)
// Parse the path string and parse out the file suffix name
String getFilenameExtension(String path)
// Compare two strings to determine whether they are the same path. Will automatically handle the ".." in the path
boolean pathEquals(String path1, String path2)
//Remove the suffix part in the file path name
String stripFilenameExtension(String path)
// Use ". as the separator to get the last part of it
String unqualify(String qualifiedName)
// Use the specified character as the delimiter to get the last part of it
String unqualify(String qualifiedName, char separator)

CollectionUtils

  1. Set judgment tool.

// Determine whether List/Set is empty
boolean isEmpty(Collection<?> collection)
// Determine whether Map is empty
boolean isEmpty(Map<?,?> map)
// Determine whether the List/Set contains an object
boolean containsInstance(Collection<?> collection, Object element)
//Use an iterator to determine whether the List/Set contains an object
boolean contains(Iterator<?> iterator, Object element)
// Determine whether List/Set contains any one of certain objects
boolean containsAny(Collection<?> source, Collection<?> candidates)
// Determine whether each element in the List/Set is unique. That is, there are no duplicate elements in List/Set
boolean hasUniqueObject(Collection<?> collection)
  1. Collection operation tools.

//Add all elements in Array to List/Set
<E> void mergeArrayIntoCollection(Object array, Collection<E> collection)
//Add all key-value pairs in Properties to the Map
<K,V> void mergePropertiesIntoMap(Properties props, Map<K,V> map)
// Return the last element in the List
<T> T lastElement(List<T> list)
// Return the last element in Set
<T> T lastElement(Set<T> set)
// Return the first element in parameter candidates that exists in parameter source
<E> E findFirstMatch(Collection<?> source, Collection<E> candidates)
// Returns the element of the specified type in the List/Set.
<T> T findValueOfType(Collection<?> collection, Class<T> type)
// Returns the element of the specified type in the List/Set. If the first type is not found, look for the second type, and so on
Object findValueOfType(Collection<?> collection, Class<?>[] types)
// Return the type of elements in List/Set
Class<?> findCommonElementType(Collection<?> collection)

Files, resources, IO streams

FileCopyUtils

  1. enter

//Read from file into byte array
byte[] copyToByteArray(File in)
//Read from input stream into byte array
byte[] copyToByteArray(InputStream in)
//Read into string from input stream
String copyToString(Reader in)
  1. output

//From byte array to file
void copy(byte[] in, File out)
// from file to file
int copy(File in, File out)
// From byte array to output stream
void copy(byte[] in, OutputStream out)
// From input stream to output stream
int copy(InputStream in, OutputStream out)
// From input stream to output stream
int copy(Reader in, Writer out)
// From string to output stream
void copy(String in, Writer out)

ResourceUtils

  1. Get file from resource path

//Determine whether the string is a legal URL string.
static boolean isUrl(String resourceLocation)
// Get URL
static URL getURL(String resourceLocation)
// Get the file (cannot be used normally in JAR package, needs to be an independent file)
static File getFile(String resourceLocation)
  1. Resource

//File system resources D:\...
FileSystemResource
// URL resources, such as file://... http://...
UrlResource
// Resources under the classpath, classpth:...
ClassPathResource
// Resources in the Web container context (jar package, war package)
ServletContextResource
// Determine whether the resource exists
boolean exists()
// Get the File object from the resource
File getFile()
// Get the URI object from the resource
URI getURI()
// Get the URI object from the resource
URL getURL()
// Get the InputStream of the resource
InputStream getInputStream()
// Get the description information of the resource
String getDescription()

StreamUtils

  1. enter

void copy(byte[] in, OutputStream out)
int copy(InputStream in, OutputStream out)
void copy(String in, Charset charset, OutputStream out)
long copyRange(InputStream in, OutputStream out, long start, long end)
  1. output

byte[] copyToByteArray(InputStream in)
String copyToString(InputStream in, Charset charset)
// Discard the contents of the input stream
int drain(InputStream in)

Reflection, AOP

ReflectionUtils

  1. Get method

//Find the specified method in the class
Method findMethod(Class<?> clazz, String name)
// Same as above, additional method parameter types are provided as search conditions
Method findMethod(Class<?> clazz, String name, Class<?>... paramTypes)
// Get all methods in the class, including inherited ones
Method[] getAllDeclaredMethods(Class<?> leafClass)
// Find the specified constructor method in the class
Constructor<T> accessibleConstructor(Class<T> clazz, Class<?>... parameterTypes)
// Whether it is the equals() method
boolean isEqualsMethod(Method method)
// Whether it is hashCode() method
boolean isHashCodeMethod(Method method)
// Whether it is toString() method
boolean isToStringMethod(Method method)
// Whether it is a method inherited from the Object class
boolean isObjectMethod(Method method)
// Check whether a method is declared to throw the specified exception
boolean declaresException(Method method, Class<?> exceptionType)
  1. Execution method

//Execution method
Object invokeMethod(Method method, Object target)
// Same as above, provide method parameters
Object invokeMethod(Method method, Object target, Object... args)
// Cancel Java permission check. for subsequent execution of the private method
void makeAccessible(Method method)
// Cancel Java permission check. for subsequent execution of the private constructor
void makeAccessible(Constructor<?> ctor)
  1. Get fields

//Find the specified attribute in the class
Field findField(Class<?> clazz, String name)
// Same as above, additional attribute types are provided.
Field findField(Class<?> clazz, String name, Class<?> type)
// Whether it is a "public static final" property
boolean isPublicStaticFinal(Field field)
  1. Set fields

//Get the field attribute value of the target object
Object getField(Field field, Object target)
//Set the field attribute value of the target object, the value is value
void setField(Field field, Object target, Object value)
// Equivalent assignment of attributes of similar objects
void shallowCopyFieldState(Object src, Object dest)
// Cancel Java's permission control checks. for subsequent reading and writing of the private property
void makeAccessible(Field field)
//Execute callback for each property of the class
void doWithFields(Class<?> clazz, ReflectionUtils.FieldCallback fc)
// Same as above, with an additional attribute filtering function.
void doWithFields(Class<?> clazz, ReflectionUtils.FieldCallback fc,
                  ReflectionUtils.FieldFilter ff)
// Same as above, but excluding inherited properties
void doWithLocalFields(Class<?> clazz, ReflectionUtils.FieldCallback fc)

AopUtils

  1. Determine agent type

// Determine whether it is a Spring proxy object
boolean isAopProxy()
// Determine whether it is a jdk dynamic proxy object
isJdkDynamicProxy()
// Determine whether it is a CGLIB proxy object
boolean isCglibProxy()
  1. Get the class of the proxy object

//Get the proxy target class
Class<?> getTargetClass()

AopContext

  1. Get the proxy object of the current object

Object currentProxy()

Author:CadeCode

https://juejin.cn/post/7043403364020781064

If the source of the content published in the public account "Java Selection" is indicated, the copyright belongs to the original source (the content whose copyright cannot be verified or the source is not indicated is from the Internet and is reprinted. The purpose of reprinting is to convey more information. The copyright belongs to the original author. If there is any infringement, please contact us and we will delete it as soon as possible!
Recently, many people have asked if there is a reader exchange group! The method to join is very simple, just select the public account Java and reply "Add group" to join the group!

Java Selected Interview Questions: 3000+ interview questions, including Java basics, concurrency, JVM, threads, MQ series, Redis, Spring series, Elasticsearch, Docker, K8s, Flink, Spark, architecture design, etc., online at any time Refresh the questions!
------ Special recommendation ------
Special recommendation: "Big Shot Notes" is a public account that focuses on sharing the most cutting-edge technology and information, preparing for overtaking in corners, and various open source projects and high-efficiency software. It focuses on digging out good things and is very worthy of everyone's attention. Click on the public account card below to follow.

Click "Read the original text" to learn more exciting content! If the article is helpful, please click to read and forward it!