Most of our projects are based on the Spring architecture, and Spring itself contains many useful tool classes. Learning how to use these tool classes not only enables us to achieve twice the result with half the effort, but also reduces the introduction of unnecessary additional tool classes. When we look at the source code of these utility classes, we find that they are of type Abstract. This is because the methods of utility classes are generally static. Static methods are bound to the class and can be used once the class is loaded without instantiation. Therefore, the definition of the utility class as an Abstract type is appropriate.
Print (system.out.println);
private static void print(Object value) {
System.out.println(value);
}
Copy the code
ClassUtils
Org. Springframework. Util. ClassUtils contains some and Java lang. Class related practical method.
getDefaultClassLoader
ClassLoader getDefaultClassLoader() gets the ClassLoader for the current thread context:
print(ClassUtils.getDefaultClassLoader());
Copy the code
sun.misc.Launcher$AppClassLoader@18b4aac2
Copy the code
overrideThreadContextClassLoader
This overrideThreadContextClassLoader (@ Nullable this classLoaderToUse) cover the current thread context with a specific class loader class loader:
print(ClassUtils.getDefaultClassLoader());
ClassUtils.overrideThreadContextClassLoader(ClassLoader.getSystemClassLoader().getParent());
print(ClassUtils.getDefaultClassLoader());
Copy the code
sun.misc.Launcher$AppClassLoader@18b4aac2
sun.misc.Launcher$ExtClassLoader@3feba861
Copy the code
forName
ForName (String name, @nullable ClassLoader ClassLoader) returns an instance of a Class by its Class name, similar to class.forname () but more powerful. It can be used for primitive types, inner classes, etc. :
ClassLoader classLoader = ClassUtils.getDefaultClassLoader();
print(ClassUtils.forName("int", classLoader));
print(ClassUtils.forName("java.lang.String[]", classLoader));
print(ClassUtils.forName("java.lang.Thread$State", classLoader));
Copy the code
int
class [Ljava.lang.String;
class java.lang.Thread$State
Copy the code
isPresent
Boolean isPresent(String className, @nullable ClassLoader ClassLoader) Determines whether the current ClassLoader contains the target type (including all its parents and interfaces) :
ClassLoader classLoader = ClassUtils.getDefaultClassLoader();
print(ClassUtils.isPresent("int", classLoader));
print(ClassUtils.isPresent("intt", classLoader));
Copy the code
true
false
Copy the code
resolvePrimitiveClassName
Class
resolvePrimitiveClassName @ Nullable (String name) by a given class name for original class:
print(ClassUtils.resolvePrimitiveClassName("int"));
print(ClassUtils.resolvePrimitiveClassName("java.lang.Integer"));
Copy the code
int
null
Copy the code
isPrimitiveWrapper
boolean isPrimitiveWrapper(Class
clazz) determines whether a given class is a wrapper class, such as Boolean, Byte, Character, Short, Integer, Long, Float, Double, or Void:
print(ClassUtils.isPrimitiveWrapper(Integer.class));
print(ClassUtils.isPrimitiveWrapper(Character.class));
print(ClassUtils.isPrimitiveWrapper(Void.class));
print(ClassUtils.isPrimitiveWrapper(String.class));
Copy the code
true
true
true
false
Copy the code
Similar methods include isPrimitiveOrWrapper, isPrimitiveWrapperArray, isPrimitiveWrapperArray and isPrimitiveArray.
resolvePrimitiveIfNecessary
Class
resolvePrimitiveIfNecessary(Class
clazz) returns the corresponding wrapper class if the given class is primitive, otherwise returns the given class directly:
print(ClassUtils.resolvePrimitiveIfNecessary(int.class));
print(ClassUtils.resolvePrimitiveIfNecessary(Object.class));
Copy the code
class java.lang.Integer
class java.lang.Object
Copy the code
isAssignable
boolean isAssignable(Class
lhsType, Class
rhsType) by reflection check whether rhsType can be assigned to lhsType (note that the wrapper type can be assigned to the corresponding primitive type, auto-unboxing mechanism) :
print(ClassUtils.isAssignable(Integer.class, int.class));
print(ClassUtils.isAssignable(Object.class, String.class));
print(ClassUtils.isAssignable(BeanPostProcessor.class, InstantiationAwareBeanPostProcessor.class));
print(ClassUtils.isAssignable(double.class, Double.class)); // consider this
print(ClassUtils.isAssignable(Integer.class, Long.class));
Copy the code
true
true
true
true
false
Copy the code
isAssignableValue
boolean isAssignableValue(Class
type, @nullable Object value) determine if a given value matches a given type:
print(ClassUtils.isAssignableValue(Integer.class, 1));
print(ClassUtils.isAssignableValue(Integer.class, 1L));
print(ClassUtils.isAssignableValue(int.class, Integer.valueOf(1)));
print(ClassUtils.isAssignableValue(Object.class,1));
print(ClassUtils.isAssignableValue(String.class,1));
Copy the code
true
false
true
true
false
Copy the code
convertResourcePathToClassName
String convertResourcePathToClassName (String resourcePath) converts the classpath to the fully qualified class name:
print(ClassUtils.convertResourcePathToClassName("java/lang/String"));
Copy the code
java.lang.String
Copy the code
You’re essentially replacing theta with theta. ConvertClassNameToResourcePath method function instead.
classNamesToString
String classNamesToString(Class
… Classes) see the demo without explaining:
print(ClassUtils.classNamesToString(String.class, Integer.class, BeanPostProcessor.class));
Copy the code
[java.lang.String, java.lang.Integer, org.springframework.beans.factory.config.BeanPostProcessor]
Copy the code
getAllInterfaces
Class
[] getAllInterfaces(Object instance) returns the set of interface types implemented by the given instance Object:
AutowiredAnnotationBeanPostProcessor processor = newAutowiredAnnotationBeanPostProcessor(); Class<? >[] allInterfaces = ClassUtils.getAllInterfaces(processor); Arrays.stream(allInterfaces).forEach(System.out::println);Copy the code
interface org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor
interface org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor
interface org.springframework.core.PriorityOrdered
interface org.springframework.beans.factory.BeanFactoryAware
Copy the code
A similar approach and getAllInterfacesForClass, getAllInterfacesAsSet, getAllInterfacesForClassAsSet
determineCommonAncestor
Class
determineCommonAncestor(@Nullable Class
clazz1, @Nullable Class
clazz2) Find the common ancestor of the given type (the common ancestor is the common type obtained by calling class.getsuperclass for the given type, if the given type is Object.class, interface, primitive type or Void, return null) :
// Both are interfaces
print(ClassUtils.determineCommonAncestor(AutowireCapableBeanFactory.class, ListableBeanFactory.class));
print(ClassUtils.determineCommonAncestor(Long.class, Integer.class));
print(ClassUtils.determineCommonAncestor(String.class, Integer.class));
null
class java.lang.Number
null
Copy the code
isInnerClass
boolean isInnerClass(Class
clazz) determines whether a given type is an inner class (non-static) :
class A {
class B {
}
}
print(ClassUtils.isInnerClass(A.B.class)); // true
Copy the code
static class A {
class B {
}
}
print(ClassUtils.isInnerClass(A.B.class)); // true
static class A {
static class B {
}
}
print(ClassUtils.isInnerClass(A.B.class)); // false
Copy the code
isCglibProxy
Boolean isCglibProxy(Object Object) Specifies whether it is a Cglib proxy Object:
@SpringBootApplication
public class AopApplication {
@Configuration
static class MyConfigure {}public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(AopApplication.class, args); MyConfigure myConfigure = context.getBean(MyConfigure.class); System.out.println(ClassUtils.isCglibProxy(myConfigure)); }}Copy the code
true
Copy the code
If the configuration class is not represented by Cglib, return false:
@SpringBootApplication
public class AopApplication {
@Configuration(proxyBeanMethods = false) // Notice here
static class MyConfigure {}public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(AopApplication.class, args); MyConfigure myConfigure = context.getBean(MyConfigure.class); System.out.println(ClassUtils.isCglibProxy(myConfigure)); }}Copy the code
false
Copy the code
Abandoned this approach, however, it is recommended to use org. Springframework. Aop. Support. AopUtils. IsCglibProxy (Object) method.
getUserClass
Class
getUserClass(Object instance) returns the type of the given instance, or the target Object type of the proxy if the instance is the Object behind the Cglib proxy:
print(ClassUtils.getUserClass("Hello")); // class java.lang.String
Copy the code
Cglib proxy examples:
@SpringBootApplication
public class AopApplication {
@Configuration
static class MyConfigure {}public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(AopApplication.class, args);
MyConfigure myConfigure = context.getBean(MyConfigure.class);
// Notice the differenceSystem.out.println(myConfigure.getClass()); System.out.println(ClassUtils.getUserClass(myConfigure)); }}Copy the code
class cc.mrbird.aop.AopApplication$MyConfigure$$EnhancerBySpringCGLIB$$e51ce45
class cc.mrbird.aop.AopApplication$MyConfigure
Copy the code
matchesTypeName
boolean matchesTypeName(Class
clazz, @nullable String typeName)
print(ClassUtils.matchesTypeName(String.class, "java.lang.String")); // true
Copy the code
getShortName
String getShortName(Class
clazz) returns the class name:
print(ClassUtils.getShortName(String.class)); // String
Copy the code
getShortNameAsProperty
String getShortNameAsProperty(Class
clazz) returns the class name in lower case, with the outer name removed if the class is inner:
print(ClassUtils.getShortNameAsProperty(String.class)); // string
Copy the code
class A {
class B {
}
}
print(ClassUtils.getShortNameAsProperty(String.class)); // b
Copy the code
getClassFileName
String getClassFileName(Class
clazz) returns the class name +.class:
print(ClassUtils.getShortNameAsProperty(String.class)); // String.class
Copy the code
getPackageName
String getPackageName(Class
clazz) return package name:
print(ClassUtils.getShortNameAsProperty(String.class)); // java.lang
Copy the code
getQualifiedName
String getQualifiedName(Class
clazz) returns the fully qualified class name, followed by [] :
print(ClassUtils.getQualifiedName(String.class));
print(ClassUtils.getQualifiedName(String[].class));
Copy the code
java.lang.String
java.lang.String[]
Copy the code
getQualifiedMethodName
String getQualifiedMethodName(Method Method) Gets the fully qualified name of the Method:
print(ClassUtils.getQualifiedMethodName(
ClassUtils.class.getDeclaredMethod("getQualifiedMethodName", Method.class
)));
Copy the code
org.springframework.util.ClassUtils.getQualifiedMethodName
Copy the code
hasConstructor
boolean hasConstructor(Class
clazz, Class
… ParamTypes) determines whether a given type has a given type parameter constructor:
print(ClassUtils.hasConstructor(String.class, String.class));
print(ClassUtils.hasConstructor(String.class, Object.class));
Copy the code
true
false
Copy the code
getConstructorIfAvailable
Constructor
getConstructorIfAvailable(Class
clazz, Class
… ParamTypes) returns the given argument type constructor for the given type, or null if none:
Constructor<String> constructorIfAvailable = ClassUtils.getConstructorIfAvailable(String.class, String.class); print(constructorIfAvailable ! =null);
print(constructorIfAvailable.toString());
Copy the code
true
public java.lang.String(java.lang.String)
Copy the code
hasMethod
boolean hasMethod(Class
clazz, Method Method) determines whether a given type has a specified Method:
Method hasMethod = ClassUtils.class.getDeclaredMethod("hasMethod", Class.class, Method.class);
print(ClassUtils.hasMethod(ClassUtils.class, hasMethod)); // true
Copy the code
Boolean hasMethod(Class
clazz, String methodName, Class
… ParamTypes).
getMethod
Method getMethod(Class
clazz, String methodName, @Nullable Class
… ParamTypes) find IllegalStateException exception from specified type;
ClassUtils.getMethod(ClassUtils.class,"hello", String.class);
Copy the code
java.lang.IllegalStateException: Expected method not found: java.lang.NoSuchMethodException: org.springframework.util.ClassUtils.hello(java.lang.String)
Copy the code
If you want to return null instead of throwing an exception, you can use the getMethodIfAvailable method.
getMethodCountForName
int getMethodCountForName(Class
clazz, String methodName) finds the number of methods (overridden, overloaded, non-public) from the specified type by methodName:
print(ClassUtils.getMethodCountForName(ClassUtils.class,"hasMethod")); / / 2
Copy the code
A similar approach and hasAtLeastOneMethodWithName, must have at least one.
getStaticMethod
Method getStaticMethod(Class
clazz, String methodName, Class
… Args) gets a static method of the given type, or null if the method is not static or does not exist:
Method method = ClassUtils.getStaticMethod(ClassUtils.class, "getDefaultClassLoader"); print(method ! =null);
print(method.getReturnType());
Copy the code
true
class java.lang.ClassLoader
Copy the code
FileSystemUtils
File system utility classes
deleteRecursively
Boolean deleterecururShrink (@nullable File root) Recursively delete specified files or directories without throwing an exception or returning true on success or false on failure.
The delete directory for File will try to delete directory A:
File file = new File("a");
print(file.delete()); // false
Copy the code
Since directory A contains subdirectories (files), recursive deletion should be used:
File file = new File("a");
print(FileSystemUtils.deleteRecursively(file)); // true
Copy the code
Boolean deleterecurShrink (@nullable Path root) functions similarly to this method, but this method may throw IO exceptions.
copyRecursively
Void copyRecursively copy the SRC File to dest without making the target path exist:
File src = new File("a");
File dest = new File("aa");
FileSystemUtils.copyRecursively(src, dest);
Copy the code
Overloaded method void copyrecurshrink (Path SRC, Path dest).
StreamUtils
A utility method that contains some file streams has a default buffer size of 4096bytes.
Note: None of the methods of this utility class will close the stream!