SpringBoot 内置工具类的使用

目录
  • 断言
  • 对象、数组、集合
    • ObjectUtils
    • StringUtils
    • CollectionUtils
  • 文件、资源、IO 流
    • FileCopyUtils
    • ResourceUtils
    • StreamUtils
  • 反射、AOP
    • ReflectionUtils
    • AopUtils
    • AopContext

断言

  • 断言是一个逻辑判断,用于检查不应该发生的情况
  • Assert 关键字在 JDK1.4 中引入,可通过 JVM 参数-enableassertions开启
  • SpringBoot 中提供了 Assert 断言工具类,通常用于数据合法性检查
// 要求参数 object 必须为非空(Not Null),否则抛出异常,不予放行
// 参数 message 参数用于定制异常信息。
void notNull(Object object, String message)
// 要求参数必须空(Null),否则抛出异常,不予『放行』。
// 和 notNull() 方法断言规则相反
void isNull(Object object, String message)
// 要求参数必须为真(True),否则抛出异常,不予『放行』。
void isTrue(boolean expression, String message)
// 要求参数(List/Set)必须非空(Not Empty),否则抛出异常,不予放行
void notEmpty(Collection collection, String message)
// 要求参数(String)必须有长度(即,Not Empty),否则抛出异常,不予放行
void hasLength(String text, String message)
// 要求参数(String)必须有内容(即,Not Blank),否则抛出异常,不予放行
void hasText(String text, String message)
// 要求参数是指定类型的实例,否则抛出异常,不予放行
void isInstanceOf(Class type, Object obj, String message)
// 要求参数 `subType` 必须是参数 superType 的子类或实现类,否则抛出异常,不予放行
void isAssignable(Class superType, Class subType, String message)

对象、数组、集合

ObjectUtils

获取对象的基本信息

// 获取对象的类名。参数为 null 时,返回字符串:"null"
String nullSafeClassName(Object obj)
// 参数为 null 时,返回 0
int nullSafeHashCode(Object object)
// 参数为 null 时,返回字符串:"null"
String nullSafeToString(boolean[] array)
// 获取对象 HashCode(十六进制形式字符串)。参数为 null 时,返回 0
String getIdentityHexString(Object obj)
// 获取对象的类名和 HashCode。 参数为 null 时,返回字符串:""
String identityToString(Object obj)
// 相当于 toString()方法,但参数为 null 时,返回字符串:""
String getDisplayString(Object obj)

判断工具

// 判断数组是否为空
boolean isEmpty(Object[] array)
// 判断参数对象是否是数组
boolean isArray(Object obj)
// 判断数组中是否包含指定元素
boolean containsElement(Object[] array, Object element)
// 相等,或同为 null时,返回 true
boolean nullSafeEquals(Object o1, Object o2)
/*
判断参数对象是否为空,判断标准为:
    Optional: Optional.empty()
       Array: length == 0
CharSequence: length == 0
  Collection: Collection.isEmpty()
         Map: Map.isEmpty()
 */
boolean isEmpty(Object obj)

其他工具方法

// 向参数数组的末尾追加新元素,并返回一个新数组
<A, O extends A> A[] addObjectToArray(A[] array, O obj)
// 原生基础类型数组 --> 包装类数组
Object[] toObjectArray(Object source)

StringUtils

字符串判断工具

// 判断字符串是否为 null,或 ""。注意,包含空白符的字符串为非空
boolean isEmpty(Object str)
// 判断字符串是否是以指定内容结束。忽略大小写
boolean endsWithIgnoreCase(String str, String suffix)
// 判断字符串是否已指定内容开头。忽略大小写
boolean startsWithIgnoreCase(String str, String prefix)
// 是否包含空白符
boolean containsWhitespace(String str)
// 判断字符串非空且长度不为 0,即,Not Empty
boolean hasLength(CharSequence str)
// 判断字符串是否包含实际内容,即非仅包含空白符,也就是 Not Blank
boolean hasText(CharSequence str)
// 判断字符串指定索引处是否包含一个子串。
boolean substringMatch(CharSequence str, int index, CharSequence substring)
// 计算一个字符串中指定子串的出现次数
int countOccurrencesOf(String str, String sub)

字符串操作工具

// 查找并替换指定子串
String replace(String inString, String oldPattern, String newPattern)
// 去除尾部的特定字符
String trimTrailingCharacter(String str, char trailingCharacter)
// 去除头部的特定字符
String trimLeadingCharacter(String str, char leadingCharacter)
// 去除头部的空白符
String trimLeadingWhitespace(String str)
// 去除头部的空白符
String trimTrailingWhitespace(String str)
// 去除头部和尾部的空白符
String trimWhitespace(String str)
// 删除开头、结尾和中间的空白符
String trimAllWhitespace(String str)
// 删除指定子串
String delete(String inString, String pattern)
// 删除指定字符(可以是多个)
String deleteAny(String inString, String charsToDelete)
// 对数组的每一项执行 trim() 方法
String[] trimArrayElements(String[] array)
// 将 URL 字符串进行解码
String uriDecode(String source, Charset charset)

路径相关工具方法

// 解析路径字符串,优化其中的 “..”
String cleanPath(String path)
// 解析路径字符串,解析出文件名部分
String getFilename(String path)
// 解析路径字符串,解析出文件后缀名
String getFilenameExtension(String path)
// 比较两个两个字符串,判断是否是同一个路径。会自动处理路径中的 “..”
boolean pathEquals(String path1, String path2)
// 删除文件路径名中的后缀部分
String stripFilenameExtension(String path)
// 以 “. 作为分隔符,获取其最后一部分
String unqualify(String qualifiedName)
// 以指定字符作为分隔符,获取其最后一部分
String unqualify(String qualifiedName, char separator)

CollectionUtils

集合判断工具

// 判断 List/Set 是否为空
boolean isEmpty(Collection<?> collection)
// 判断 Map 是否为空
boolean isEmpty(Map<?,?> map)
// 判断 List/Set 中是否包含某个对象
boolean containsInstance(Collection<?> collection, Object element)
// 以迭代器的方式,判断 List/Set 中是否包含某个对象
boolean contains(Iterator<?> iterator, Object element)
// 判断 List/Set 是否包含某些对象中的任意一个
boolean containsAny(Collection<?> source, Collection<?> candidates)
// 判断 List/Set 中的每个元素是否唯一。即 List/Set 中不存在重复元素
boolean hasUniqueObject(Collection<?> collection)

集合操作工具

// 将 Array 中的元素都添加到 List/Set 中
<E> void mergeArrayIntoCollection(Object array, Collection<E> collection)
// 将 Properties 中的键值对都添加到 Map 中
<K,V> void mergePropertiesIntoMap(Properties props, Map<K,V> map)
// 返回 List 中最后一个元素
<T> T lastElement(List<T> list)
// 返回 Set 中最后一个元素
<T> T lastElement(Set<T> set)
// 返回参数 candidates 中第一个存在于参数 source 中的元素
<E> E findFirstMatch(Collection<?> source, Collection<E> candidates)
// 返回 List/Set 中指定类型的元素。
<T> T findValueOfType(Collection<?> collection, Class<T> type)
// 返回 List/Set 中指定类型的元素。如果第一种类型未找到,则查找第二种类型,以此类推
Object findValueOfType(Collection<?> collection, Class<?>[] types)
// 返回 List/Set 中元素的类型
Class<?> findCommonElementType(Collection<?> collection)

文件、资源、IO 流

FileCopyUtils

输入

// 从文件中读入到字节数组中
byte[] copyToByteArray(File in)
// 从输入流中读入到字节数组中
byte[] copyToByteArray(InputStream in)
// 从输入流中读入到字符串中
String copyToString(Reader in)

输出

// 从字节数组到文件
void copy(byte[] in, File out)
// 从文件到文件
int copy(File in, File out)
// 从字节数组到输出流
void copy(byte[] in, OutputStream out)
// 从输入流到输出流
int copy(InputStream in, OutputStream out)
// 从输入流到输出流
int copy(Reader in, Writer out)
// 从字符串到输出流
void copy(String in, Writer out)

ResourceUtils

从资源路径获取文件

// 判断字符串是否是一个合法的 URL 字符串。
static boolean isUrl(String resourceLocation)
// 获取 URL
static URL getURL(String resourceLocation)
// 获取文件(在 JAR 包内无法正常使用,需要是一个独立的文件)
static File getFile(String resourceLocation)

Resource

// 文件系统资源 D:\...
FileSystemResource
// URL 资源,如 file://... http://...
UrlResource
// 类路径下的资源,classpth:...
ClassPathResource
// Web 容器上下文中的资源(jar 包、war 包)
ServletContextResource
// 判断资源是否存在
boolean exists()
// 从资源中获得 File 对象
File getFile()
// 从资源中获得 URI 对象
URI getURI()
// 从资源中获得 URI 对象
URL getURL()
// 获得资源的 InputStream
InputStream getInputStream()
// 获得资源的描述信息
String getDescription()

StreamUtils

输入

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)

输出

byte[] copyToByteArray(InputStream in)
String copyToString(InputStream in, Charset charset)
// 舍弃输入流中的内容
int drain(InputStream in)

反射、AOP

ReflectionUtils

获取方法

// 在类中查找指定方法
Method findMethod(Class<?> clazz, String name)
// 同上,额外提供方法参数类型作查找条件
Method findMethod(Class<?> clazz, String name, Class<?>... paramTypes)
// 获得类中所有方法,包括继承而来的
Method[] getAllDeclaredMethods(Class<?> leafClass)
// 在类中查找指定构造方法
Constructor<T> accessibleConstructor(Class<T> clazz, Class<?>... parameterTypes)
// 是否是 equals() 方法
boolean isEqualsMethod(Method method)
// 是否是 hashCode() 方法
boolean isHashCodeMethod(Method method)
// 是否是 toString() 方法
boolean isToStringMethod(Method method)
// 是否是从 Object 类继承而来的方法
boolean isObjectMethod(Method method)
// 检查一个方法是否声明抛出指定异常
boolean declaresException(Method method, Class<?> exceptionType) 

执行方法

// 执行方法
Object invokeMethod(Method method, Object target)
// 同上,提供方法参数
Object invokeMethod(Method method, Object target, Object... args)
// 取消 Java 权限检查。以便后续执行该私有方法
void makeAccessible(Method method)
// 取消 Java 权限检查。以便后续执行私有构造方法
void makeAccessible(Constructor<?> ctor)

获取字段

// 在类中查找指定属性
Field findField(Class<?> clazz, String name)
// 同上,多提供了属性的类型
Field findField(Class<?> clazz, String name, Class<?> type)
// 是否为一个 "public static final" 属性
boolean isPublicStaticFinal(Field field)

设置字段

// 获取 target 对象的 field 属性值
Object getField(Field field, Object target)
// 设置 target 对象的 field 属性值,值为 value
void setField(Field field, Object target, Object value)
// 同类对象属性对等赋值
void shallowCopyFieldState(Object src, Object dest)
// 取消 Java 的权限控制检查。以便后续读写该私有属性
void makeAccessible(Field field)
// 对类的每个属性执行 callback
void doWithFields(Class<?> clazz, ReflectionUtils.FieldCallback fc)
// 同上,多了个属性过滤功能。
void doWithFields(Class<?> clazz, ReflectionUtils.FieldCallback fc,
                  ReflectionUtils.FieldFilter ff)
// 同上,但不包括继承而来的属性
void doWithLocalFields(Class<?> clazz, ReflectionUtils.FieldCallback fc)

AopUtils

判断代理类型

// 判断是不是 Spring 代理对象
boolean isAopProxy()
// 判断是不是 jdk 动态代理对象
isJdkDynamicProxy()
// 判断是不是 CGLIB 代理对象
boolean isCglibProxy()

获取被代理对象的 class

// 获取被代理的目标 class
Class<?> getTargetClass()

AopContext

获取当前对象的代理对象

Object currentProxy()

到此这篇关于SpringBoot 内置工具类的使用的文章就介绍到这了,更多相关SpringBoot 内置工具类内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Springboot内置tomcat配置虚拟路径过程解析

    在Springboot中默认的静态资源路径有:classpath:/METAINF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,从这里可以看出这里的静态资源路径都是在classpath中(也就是在项目路径下指定的这几个文件夹) 试想这样一种情况:一个网站有文件上传文件的功能,如果被上传的文件放在上述的那些文件夹中会有怎样的后果? 网站数据与程序代码不能有效分离: 当项目被打包成一个.jar文件部署时

  • SpringBoot内置tomcat调优测试优化

    问题 怎么配置springBoot 内置tomcat,才能使得自己的服务效率更高呢? 基础配置 Spring Boot 能支持的最大并发量主要看其对Tomcat的设置,可以在配置文件中对其进行更改.我们可以看到默认设置中,Tomcat的最大线程数是200,最大连接数是10000. 这个不同SpringBoot 版本可能有所细微差别.本文测试基于Springboot 2.0.7.RELEASE 默认配置 /** * Maximum amount of worker threads. */ priv

  • SpringBoot内置tomcat启动原理详解

    前言 不得不说SpringBoot的开发者是在为大众程序猿谋福利,把大家都惯成了懒汉,xml不配置了,连tomcat也懒的配置了,典型的一键启动系统,那么tomcat在springboot是怎么启动的呢? 内置tomcat 开发阶段对我们来说使用内置的tomcat是非常够用了,当然也可以使用jetty. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-bo

  • 使用SpringBoot内置web服务器

    目录 一.SpringBoot默认web服务器? 二.如何配置当前web容器? 三.内嵌Web服务器如何切换(从tomcat到jetty)? 四.Web容器怎么自动配置? 五.web容器启动源码解析? 六.SpringBoot内置服务器不使用SPI机制特别说明? 本文介绍SpringBoot内置web服务器.知识点有SpringBoot默认web服务器:如何配置当前web容器:内嵌Web服务器如何切换(从tomcat到jetty):Web容器怎么自动配置:web容器启动源码解析:SpringBo

  • springboot项目中实现访问druid内置监控页面

    springboot 访问druid内置监控页面 1.首先加入druid依赖 <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.9</version> </dependency> 2.设置配置文件: # 数据库访问配置 # 主数据源,默认的 spr

  • 详解springboot-修改内置tomcat版本

    详解springboot-修改内置tomcat版本 1.解析Spring Boot父级依赖 <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.6.RELEASE</version> </parent> 这块配置就是Spring

  • SpringBoot深入理解之内置web容器及配置的总结

    前言 在学会基本运用SpringBoot同时,想必搭过SSH.SSM等开发框架的小伙伴都有疑惑,SpringBoot在spring的基础上做了些什么,使得使用SpringBoot搭建开发框架能如此简单,便捷,快速.本系列文章记录网罗博客.分析源码.结合微薄经验后的总结,以便日后翻阅自省. 正文 使用SpringBoot时,首先引人注意的便是其启动方式,我们熟知的web项目都是需要部署到服务容器上,例如tomcat.weblogic.widefly(以前叫JBoss),然后启动web容器真正运行我

  • SpringBoot 内置工具类的使用

    目录 断言 对象.数组.集合 ObjectUtils StringUtils CollectionUtils 文件.资源.IO 流 FileCopyUtils ResourceUtils StreamUtils 反射.AOP ReflectionUtils AopUtils AopContext 断言 断言是一个逻辑判断,用于检查不应该发生的情况 Assert 关键字在 JDK1.4 中引入,可通过 JVM 参数-enableassertions开启 SpringBoot 中提供了 Assert

  • Springboot内置的工具类之CollectionUtils示例讲解

    前言 实际业务开发中,集合的判断和操作也是经常用到的,Spring也针对集合的判断和操作封装了一些方法,但是最令我惊讶的是,我在梳理这些内容的过程中发现了一些有趣的现象,我的第一反应是不敢相信,再想一想,没错,我是对的.所以强烈建议大家可以认真看完这篇文章,这一篇绝对有价值,因为有趣的是我我竟然发现了Spring的两个bug. org.springframework.util.CollectionUtils 集合的判断 boolean hasUniqueObject(Collection col

  • 浅谈springboot内置tomcat和外部独立部署tomcat的区别

    前两天,我去面了个试,面试官问了我个问题,独立部署的tomcat跟springboot内置的tomcat有什么区别,为什么存在要禁掉springboot的tomcat然后将项目部署到独立的tomcat当中? 我就想,不都一个样?独立部署的tomcat可以配置优化?禁AJP,开多线程,开nio?而且springboot内置的tomcat多方便,部署上服务器写个java脚本运行即可.现在考虑下有什么条件能优于内置tomcat的. 1.tomcat的优化配置多线程?内置的也可以配置多线程 server

  • python matplotlib工具栏源码探析二之添加、删除内置工具项的案例

    从matplotlib工具栏源码探析一(禁用工具栏.默认工具栏和工具栏管理器三种模式的差异)一文可知matplotlib内置实现了多个工具项的实现,而默认工具栏中的工具项只是其中的一部分,有没有方法直接管理工具栏,添加.删除内置工具项? matplotlib内置的工具项 由源码可知,matplotlib.backend_tools.default_tools变量为字典类型,实例化了基于matplotlib.backend_tools.ToolBase类定义的内置工具项. 源码 default_t

  • springboot内置tomcat之NIO处理流程一览

    目录 前言 tomcat组件 Acceptor组件 Poller 总结 大致流程为 相较于BIO模型的tomcat,NIO的优势分析 前言 springboot内置的tomcat目前默认是基于NIO来实现的,本文介绍下tomcat接受请求的一些组件及组件之间的关联 tomcat组件 本文只介绍NIO中tomcat的组件 我们直接看NIO的核心类NioEndpoint的startInternal方法 Acceptor组件 public void startInternal() throws Exc

  • springboot内置tomcat调优并发线程数解析

    目录 前言 参数 线程池核心线程数 线程池最大线程数 请求最大连接数 accept-count tomcat线程池处理机制 总结 前言 本文解析springboot内置tomcat调优并发线程数的一些参数,并结合源码进行分析 参数 线程池核心线程数 server.tomcat.min-spare-threads:该参数为tomcat处理业务的核心线程数大小,默认值为10 线程池最大线程数 server.tomcat.max-threads:该参数为tomcat处理业务的最大线程数大小,默认值为2

  • SpringBoot内置数据源的持久化与解决方案

    目录 数据层解决方案 与SQL有关的解决方案 SpringBoot提供了3种内嵌的数据源对象供开发者选择 内置持久化解决方案 Springboot内置数据库 数据层解决方案 SQL NoSQL 与SQL有关的解决方案 现有数据层解决方案技术选型 Druid + MyBatis-Plus + MySQL 数据源:DruidDataSource 持久化技术:MyBatis-Plus / MyBatis 数据库:MySQL SpringBoot提供了3种内嵌的数据源对象供开发者选择 HikariCP

  • PHP使用内置dir类实现目录遍历删除

    本文实例讲述了PHP使用内置dir类实现目录遍历删除的方法.分享给大家供大家参考.具体实现方法如下: function clearDir($dir) { if (file_exists($dir)) { if(!is_dir($dir)) exit("{$dir}不是一个目录"); else { $dirObj = dir($dir); while ($file = $dirObj->read()) { if (is_dir($dir .'/'. $file) &&

随机推荐