Java工具类SpringBoot内置工具类

一、org.apache.commons.io.IOUtils

closeQuietly()  
toString()  
copy()  
toByteArray()  
write()  
toInputStream()  
readLines()  
copyLarge()  
lineIterator()  
readFully()  

二、org.apache.commons.io.FileUtils

deleteDirectory()  
readFileToString()  
deleteQuietly()  
copyFile()  
writeStringToFile()  
forceMkdir()  
write()  
listFiles()  
copyDirectory()  
forceDelete() 

三、org.apache.commons.lang.StringUtils

isBlank()  
isNotBlank()  
isEmpty()  
isNotEmpty()  
equals()  
join()  
split()  
EMPTY  
trimToNull()  
replace()  

四、org.apache.http.util.EntityUtils

toString()  
consume()  
toByteArray()  
consumeQuietly()  
getContentCharSet() 

五、org.apache.commons.lang3.StringUtils

isBlank()  
isNotBlank()  
isEmpty()  
isNotEmpty()  
join()  
equals()  
split()  
EMPTY  
replace()  
capitalize()  

六、org.apache.commons.io.FilenameUtils

getExtension()  
getBaseName()  
getName()  
concat()  
removeExtension()  
normalize()  
wildcardMatch()  
separatorsToUnix()  
getFullPath()  
isExtension()  

七、org.springframework.util.StringUtils

hasText()  
hasLength()  
isEmpty()  
commaDelimitedListToStringArray()  
collectionToDelimitedString()  
replace()  
delimitedListToStringArray()  
uncapitalize()  
collectionToCommaDelimitedString()  
tokenizeToStringArray()  

八、org.apache.commons.lang.ArrayUtils

contains()  
addAll()  
clone()  
isEmpty()  
add()  
EMPTY_BYTE_ARRAY  
subarray()  
indexOf()  
isEquals()  
toObject()  

九、org.apache.commons.lang.StringEscapeUtils

escapeHtml()  
unescapeHtml()  
escapeXml()  
escapeSql()  
unescapeJava()  
escapeJava()  
escapeJavaScript()  
unescapeXml()  
unescapeJavaScript()

十、org.apache.http.client.utils.URLEncodedUtils

format()  
parse() 

十一、org.apache.commons.codec.digest.DigestUtils

md5Hex()  
shaHex()  
sha256Hex()  
sha1Hex()  
sha()  
md5()  
sha512Hex()  
sha1()  

十二、org.apache.commons.collections.CollectionUtils

isEmpty()  
isNotEmpty()  
select()  
transform()  
filter()  
find()  
collect()  
forAllDo()  
addAll()  
isEqualCollection() 

十三、org.apache.commons.lang3.ArrayUtils

contains()  
isEmpty()  
isNotEmpty()  
add()  
clone()  
addAll()  
subarray()  
indexOf()  
EMPTY_OBJECT_ARRAY  
EMPTY_STRING_ARRAY  

十四、org.apache.commons.beanutils.PropertyUtils

getProperty()  
setProperty()  
getPropertyDescriptors()  
isReadable()  
copyProperties()  
getPropertyDescriptor()  
getSimpleProperty()  
isWriteable()  
setSimpleProperty()  
getPropertyType()  

十五、org.apache.commons.lang3.StringEscapeUtils

unescapeHtml4()  
escapeHtml4()  
escapeXml()  
unescapeXml()  
escapeJava()  
escapeEcmaScript()  
unescapeJava()  
escapeJson()  
escapeXml10()  

十六、org.apache.commons.beanutils.BeanUtils

copyProperties()  
getProperty()  
setProperty()  
describe()  
populate()  
copyProperty()  
cloneBean() 

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流

输入

// 从文件中读入到字节数组中
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()

断言Assert

Assert关键字在JDK1.4中引入,通过JVM参数-enableassertion开启
SpringBoot中提供了Assert断言工具类,用于数据合法性检查

//要求参数object必须为非空,否则抛出异常。message参数为定制异常信息
void notNull(Object object,String message);

void isNull(Object object,String message);//同上相反

//表达式必须为真,否则抛出异常
void isTrue(boolean expression,String message);

//要求参数list/set必须为非空,否则抛出异常
void notEmpty(Collection collection String message);

//要求参数string必须有长度,否则抛出异常
void hasLength(String text,String message);

//要求参数必须有内容,否则抛出异常
void hasText(String text,String message);

//要求参数是指定类型的实例,否则抛出异常
void isInstanceOf(Class type,Object obj,String message);

//要求参数subType必须是参数superType的子类,否则抛出异常
void isAssignable(Class superType,Class subType,String message);
public class Assert {

    /**
     * 通用处理对外抛异常,用系统统一异常管理机制
     *
     * @param expression      true 正常,false 异常,需要对外抛出异常
     * @param messageSupplier 异常消息
     */
    public static void isTrue(boolean expression, Supplier<String> messageSupplier) {
        if (!expression) {
            throw new ShopException(nullSafeGet(messageSupplier));
        }
    }

    private static String nullSafeGet(Supplier<String> messageSupplier) {
        return (messageSupplier != null ? messageSupplier.get() : null);
    }
}

ObjectUtils

获取对象的基本信息

//获取对象的类名,参数null,即返回字符串"null"
String nullSafeClassName(Object obj);

//参数为null,返回0
int nullsafeHashCode();

//参数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 01,Object o2);

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);

//判断字符串是否包含实际内容,即是不是空白
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);

//删除文件路径后缀部分
String stripFilenameExtension(String path);

//比较两个字符串,判断是否是同一个路径,会自动处理路径中的..
boolean pathEquals(String path1,String path2);

//以.为分隔符,获取其最后一部分
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(Interator<?> iterator,Object element);

//判断list/set是否包含某些对象中的任意一个
boolean containsAny(Collection<?> source,Collection<?> candidates);

//判断list/set中的每个元素是否唯一,不存在重复元素
boolean hasUniqueObject(Colleciton<?> 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)

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)
/**
 * 文件工具类
 *
 * @author siguiyang
 */
public class FileUtil {

    /**
     * 获取远程文件流<br />
     * 接收类型为http 或者 https方式
     *
     * @param file 远程文件全路径
     */
    public static DataInputStream getRemoteFile(String file) throws Exception {
        URL url = new URL(file);
        return new DataInputStream(url.openStream());
    }

    /**
     * 文件输出复制
     *
     * @param in  输入流
     * @param out 输出流
     */
    public static void write(InputStream in, OutputStream out) throws Exception {
        //创建缓冲区
        byte[] buffer = new byte[1024];
        int len;
        //循环将输入流中的内容读取到缓冲区当中
        while ((len = in.read(buffer)) > 0) {
            //输出缓冲区的内容到浏览器,实现文件下载
            out.write(buffer, 0, len);
        }
        in.close();
        out.close();
    }

    /**
     * 获取文件的Content-Type
     *
     * @param filenameExtension 文件名称
     * @return Content-Type
     */
    public static String getContentType(String filenameExtension) {
        if (filenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (filenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (filenameExtension.equalsIgnoreCase(".jpeg") ||
                filenameExtension.equalsIgnoreCase(".jpg") ||
                filenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpg";
        }
        if (filenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (filenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (filenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (filenameExtension.equalsIgnoreCase(".pptx") ||
                filenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (filenameExtension.equalsIgnoreCase(".docx") ||
                filenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (filenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        return "image/jpg";
    }
}

ResourceUtils

从资源路径获取文件

// 判断字符串是否是一个合法的 URL 字符串。
static boolean isUrl(String resourceLocation)

// 获取 URL
static URL getURL(String resourceLocation) 

// 获取文件(在 JAR 包内无法正常使用,需要是一个独立的文件)
static File getFile(String resourceLocation)

Resource

// 文件系统资源 D:\... 公众 号:Java精选
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) 

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()

======================================================

Bean对象拷贝

/**
	使用cn.hutool.core.lang.copier的Copier
*/
public class BeanCopier<T> implements Copier<T> {

    private Object source;
    private T dest;
    private CopyOptions copyOptions;


    /**
     * 创建BeanCopier
     *
     * @param <T>    目标Bean类型
     * @param source 来源对象,可以是Bean或者Map
     * @param dest   目标Bean对象
     * @return BeanCopier
     */
    public static <T> BeanCopier<T> create(Object source, T dest) {
        return new BeanCopier<>(source, dest, CopyOptions.create().setIgnoreNullValue(Boolean.TRUE).setIgnoreError(Boolean.TRUE));
    }

    /**
     * 创建BeanCopier
     *
     * @param <T>    目标Bean类型
     * @param source 来源对象,可以是Bean或者Map
     * @param dest   目标Bean对象
     * @return BeanCopier
     */
    public static <T> T copy(Object source, T dest) {
        return create(source, dest).copy();
    }

    /**
     * 创建BeanCopier
     *
     * @param <T>         目标Bean类型
     * @param source      来源对象,可以是Bean或者Map
     * @param dest        目标Bean对象
     * @param copyOptions 拷贝属性选项
     * @return BeanCopier
     */
    public static <T> BeanCopier<T> create(Object source, T dest, CopyOptions copyOptions) {
        return new BeanCopier<>(source, dest, copyOptions);
    }

    /**
     * 构造
     *
     * @param source      来源对象,可以是Bean或者Map
     * @param dest        目标Bean对象
     * @param copyOptions 拷贝属性选项
     */
    public BeanCopier(Object source, T dest, CopyOptions copyOptions) {
        this.source = source;
        this.dest = dest;
        this.copyOptions = copyOptions;
    }

    @Override
    @SuppressWarnings("unchecked")
    public T copy() {
        if (null != this.source) {
            if (this.source instanceof ValueProvider) {
                valueProviderToBean((ValueProvider<String>) this.source, this.dest);
            } else if (this.source instanceof Map) {
                mapToBean((Map<?, ?>) this.source, this.dest);
            } else {
                beanToBean(this.source, this.dest);
            }
        }
        return this.dest;
    }

    /**
     * Bean和Bean之间属性拷贝
     *
     * @param providerBean 来源Bean
     * @param destBean     目标Bean
     */
    private void beanToBean(Object providerBean, Object destBean) {
        valueProviderToBean(new BeanValueProvider(providerBean, this.copyOptions.ignoreCase, this.copyOptions.ignoreError), destBean);
    }

    /**
     * Map转Bean属性拷贝
     *
     * @param map  Map
     * @param bean Bean
     */
    private void mapToBean(Map<?, ?> map, Object bean) {
        valueProviderToBean(new MapValueProvider(map, this.copyOptions.ignoreCase), bean);
    }

    /**
     * 值提供器转Bean
     *
     * @param valueProvider 值提供器
     * @param bean          Bean
     */
    private void valueProviderToBean(ValueProvider<String> valueProvider, Object bean) {
        if (null == valueProvider) {
            return;
        }

        Class<?> actualEditable = bean.getClass();
        if (copyOptions.editable != null) {
            // 检查限制类是否为target的父类或接口
            if (!copyOptions.editable.isInstance(bean)) {
                throw new IllegalArgumentException(StrUtil.format("Target class [{}] not assignable to Editable class [{}]", bean.getClass().getName(), copyOptions.editable.getName()));
            }
            actualEditable = copyOptions.editable;
        }
        final HashSet<String> ignoreSet = (null != copyOptions.ignoreProperties) ? CollUtil.newHashSet(copyOptions.ignoreProperties) : null;
        final Map<String, String> fieldReverseMapping = copyOptions.getReversedMapping();

        final Collection<BeanDesc.PropDesc> props = BeanUtil.getBeanDesc(actualEditable).getProps();
        String fieldName;
        Object value;
        Method setterMethod;
        Class<?> propClass;
        for (BeanDesc.PropDesc prop : props) {
            // 获取值
            fieldName = prop.getFieldName();
            if (CollUtil.contains(ignoreSet, fieldName)) {
                // 目标属性值被忽略或值提供者无此key时跳过
                continue;
            }
            final String providerKey = mappingKey(fieldReverseMapping, fieldName);
            if (!valueProvider.containsKey(providerKey)) {
                // 无对应值可提供
                continue;
            }
            setterMethod = prop.getSetter();
            if (null == setterMethod) {
                // Setter方法不存在跳过
                continue;
            }
            value = valueProvider.value(providerKey, TypeUtil.getFirstParamType(setterMethod));
            // 如果是字符串
            if (value instanceof String) {
                String v = (String) value;
                // 字符串为空,则跳过
                if (StrUtil.isBlank(v) && copyOptions.ignoreNullValue) {
                    continue;
                }
            }
            if (null == value && copyOptions.ignoreNullValue) {
                // 当允许跳过空时,跳过
                continue;
            }

            try {
                // valueProvider在没有对值做转换且当类型不匹配的时候,执行默认转换
                propClass = prop.getFieldClass();
                if (!propClass.isInstance(value)) {
                    value = Convert.convert(propClass, value);
                    if (null == value && copyOptions.ignoreNullValue) {
                        // 当允许跳过空时,跳过
                        continue;
                    }
                }

                // 执行set方法注入值
                setterMethod.invoke(bean, value);
            } catch (Exception e) {
                if (copyOptions.ignoreError) {
                    // 忽略注入失败
                    continue;
                } else {
                    throw new UtilException(e, "Inject [{}] error!", prop.getFieldName());
                }
            }
        }
    }

    /**
     * 获取指定字段名对应的映射值
     *
     * @param fieldReverseMapping 反向映射Map
     * @param fieldName           字段名
     * @return 映射值,无对应值返回字段名
     * @since 4.1.10
     */
    private static String mappingKey(Map<String, String> fieldReverseMapping, String fieldName) {
        if (MapUtil.isEmpty(fieldReverseMapping)) {
            return fieldName;
        }
        return ObjectUtil.defaultIfNull(fieldReverseMapping.get(fieldName), fieldName);
    }
}

/**
 * 属性拷贝选项<br>
 * 包括:<br>
 * 1、限制的类或接口,必须为目标对象的实现接口或父类,用于限制拷贝的属性,例如一个类我只想复制其父类的一些属性,就可以将editable设置为父类<br>
 * 2、是否忽略空值,当源对象的值为null时,true: 忽略而不注入此值,false: 注入null<br>
 * 3、忽略的属性列表,设置一个属性列表,不拷贝这些属性值<br>
 *
 * @author Looly
 */
public class CopyOptions {
    /**
     * 限制的类或接口,必须为目标对象的实现接口或父类,用于限制拷贝的属性,例如一个类我只想复制其父类的一些属性,就可以将editable设置为父类
     */
    protected Class<?> editable;
    /**
     * 是否忽略空值,当源对象的值为null时,true: 忽略而不注入此值,false: 注入null
     */
    protected boolean ignoreNullValue;
    /**
     * 忽略的目标对象中属性列表,设置一个属性列表,不拷贝这些属性值
     */
    protected String[] ignoreProperties;
    /**
     * 是否忽略字段注入错误
     */
    protected boolean ignoreError;
    /**
     * 是否忽略字段大小写
     */
    protected boolean ignoreCase;
    /**
     * 拷贝属性的字段映射,用于不同的属性之前拷贝做对应表用
     */
    protected Map<String, String> fieldMapping;

    /**
     * 创建拷贝选项
     *
     * @return 拷贝选项
     */
    public static CopyOptions create() {
        return new CopyOptions();
    }

    /**
     * 创建拷贝选项
     *
     * @param editable         限制的类或接口,必须为目标对象的实现接口或父类,用于限制拷贝的属性
     * @param ignoreNullValue  是否忽略空值,当源对象的值为null时,true: 忽略而不注入此值,false: 注入null
     * @param ignoreProperties 忽略的属性列表,设置一个属性列表,不拷贝这些属性值
     * @return 拷贝选项
     */
    public static CopyOptions create(Class<?> editable, boolean ignoreNullValue, String... ignoreProperties) {
        return new CopyOptions(editable, ignoreNullValue, ignoreProperties);
    }

    /**
     * 构造拷贝选项
     */
    public CopyOptions() {
    }

    /**
     * 构造拷贝选项
     *
     * @param editable         限制的类或接口,必须为目标对象的实现接口或父类,用于限制拷贝的属性
     * @param ignoreNullValue  是否忽略空值,当源对象的值为null时,true: 忽略而不注入此值,false: 注入null
     * @param ignoreProperties 忽略的目标对象中属性列表,设置一个属性列表,不拷贝这些属性值
     */
    public CopyOptions(Class<?> editable, boolean ignoreNullValue, String... ignoreProperties) {
        this.editable = editable;
        this.ignoreNullValue = ignoreNullValue;
        this.ignoreProperties = ignoreProperties;
    }

    /**
     * 设置限制的类或接口,必须为目标对象的实现接口或父类,用于限制拷贝的属性
     *
     * @param editable 限制的类或接口
     * @return CopyOptions
     */
    public CopyOptions setEditable(Class<?> editable) {
        this.editable = editable;
        return this;
    }

    /**
     * 设置是否忽略空值,当源对象的值为null时,true: 忽略而不注入此值,false: 注入null
     *
     * @param ignoreNullVall 是否忽略空值,当源对象的值为null时,true: 忽略而不注入此值,false: 注入null
     * @return CopyOptions
     */
    public CopyOptions setIgnoreNullValue(boolean ignoreNullVall) {
        this.ignoreNullValue = ignoreNullVall;
        return this;
    }

    /**
     * 设置忽略的目标对象中属性列表,设置一个属性列表,不拷贝这些属性值
     *
     * @param ignoreProperties 忽略的目标对象中属性列表,设置一个属性列表,不拷贝这些属性值
     * @return CopyOptions
     */
    public CopyOptions setIgnoreProperties(String... ignoreProperties) {
        this.ignoreProperties = ignoreProperties;
        return this;
    }

    /**
     * 设置是否忽略字段的注入错误
     *
     * @param ignoreError 是否忽略注入错误
     * @return CopyOptions
     */
    public CopyOptions setIgnoreError(boolean ignoreError) {
        this.ignoreError = ignoreError;
        return this;
    }

    /**
     * 设置是否忽略字段的注入错误
     *
     * @param ignoreCase 是否忽略大小写
     * @return CopyOptions
     */
    public CopyOptions setIgnoreCase(boolean ignoreCase) {
        this.ignoreCase = ignoreCase;
        return this;
    }

    /**
     * 设置拷贝属性的字段映射,用于不同的属性之前拷贝做对应表用
     *
     * @param fieldMapping 拷贝属性的字段映射,用于不同的属性之前拷贝做对应表用
     * @return CopyOptions
     */
    public CopyOptions setFieldMapping(Map<String, String> fieldMapping) {
        this.fieldMapping = fieldMapping;
        return this;
    }

    /**
     * 获取反转之后的映射
     *
     * @return 反转映射
     * @since 4.1.10
     */
    protected Map<String, String> getReversedMapping() {
        return (null != this.fieldMapping) ? MapUtil.reverse(this.fieldMapping) : null;
    }
}

时间操作工具

public class DateUtils {

    /**
     * 标准日期格式:yyyy-MM-dd
     */
    public final static String NORM_DATE_PATTERN = "yyyy-MM-dd";

    /**
     * 标准时间格式:HH:mm:ss
     */
    public final static String NORM_TIME_PATTERN = "HH:mm:ss";

    /**
     * 标准日期时间格式,精确到分:yyyy-MM-dd HH:mm
     */
    public final static String NORM_DATETIME_MINUTE_PATTERN = "yyyy-MM-dd HH:mm";

    /**
     * 标准日期时间格式,精确到秒:yyyy-MM-dd HH:mm:ss
     */
    public final static String NORM_DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";

    /**
     * 标准日期时间格式,精确到毫秒:yyyy-MM-dd HH:mm:ss.SSS
     */
    public final static String NORM_DATETIME_MS_PATTERN = "yyyy-MM-dd HH:mm:ss.SSS";

    /**
     * 标准日期格式:yyyyMMdd
     */
    public final static String PURE_DATE_PATTERN = "yyyyMMdd";
    /**
     * 标准日期格式:yyyyMM
     */
    public final static String PURE_MONTH_PATTERN = "yyyyMM";
    /**
     * 标准日期格式:mm:ss
     */
    public final static String PURE_MINUTES_PATTERN = "mm:ss";

    /**
     * 标准日期格式:HHmmss
     */
    public final static String PURE_TIME_PATTERN = "HHmmss";

    /**
     * 标准日期格式:yyyyMMddHHmmss
     */
    public final static String PURE_DATETIME_PATTERN = "yyyyMMddHHmmss";

    /**
     * 标准日期格式:yyyyMMddHHmmssSSS
     */
    public final static String PURE_DATETIME_MS_PATTERN = "yyyyMMddHHmmssSSS";

    /**
     * HTTP头中日期时间格式:EEE, dd MMM yyyy HH:mm:ss z
     */
    public final static String HTTP_DATETIME_PATTERN = "EEE, dd MMM yyyy HH:mm:ss z";

    /**
     * JDK中日期时间格式:EEE MMM dd HH:mm:ss zzz yyyy
     */
    public final static String JDK_DATETIME_PATTERN = "EEE MMM dd HH:mm:ss zzz yyyy";

    private DateUtils() {
    }


    /**
     * 当前时间
     */
    public static LocalDateTime dateTime() {
        return LocalDateTime.now();
    }

    /**
     * 获取当前时间
     */
    public static Date now() {
        return Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * 时间格式化 yyyy-MM-dd HH:mm:ss
     *
     * @param dateTime 时间
     */
    public static String formatTimeDate(final LocalDateTime dateTime) {
        return DateTimeFormatter.ofPattern(NORM_DATETIME_PATTERN).format(dateTime);
    }

    /**
     * 根据不同的 格式化规则格式时间样式
     *
     * @param dateTime 时间
     * @param pattern  格式化规则
     */
    public static String format(final LocalDateTime dateTime, final String pattern) {
        return DateTimeFormatter.ofPattern(pattern).format(dateTime);
    }


    /**
     * 转换时间
     *
     * @param parseTime 时间内容
     * @param pattern   转换格式
     */
    public static Date parse(final String parseTime, final String pattern) {

        LocalDateTime dateTime = LocalDateTime.from(DateTimeFormatter.ofPattern(pattern).parse(parseTime));

        return Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * 转换时间
     *
     * @param parseTime 时间内容
     */
    public static LocalDateTime parseTime(final String parseTime) {
        return LocalDateTime.from(DateTimeFormatter.ofPattern(NORM_DATETIME_PATTERN).parse(parseTime));
    }


    /**
     * 转换时间
     *
     * @param parseTime 时间内容
     */
    public static LocalDateTime parseTime(final String parseTime, final String pattern) {
        return LocalDateTime.from(DateTimeFormatter.ofPattern(pattern).parse(parseTime));
    }

    /**
     * 转换时间
     */
    public static LocalDateTime parseLocalDateTime(final Date date) {
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

    /**
     * 转换时间
     */
    public static LocalDate parseLocalDate(final Date date) {
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }

    /**
     * 转换时间
     *
     * @param parseTime 时间内容
     */
    public static Date parseDateTime(final String parseTime) {

        LocalDateTime dateTime = LocalDateTime.from(DateTimeFormatter.ofPattern(NORM_DATETIME_PATTERN).parse(parseTime));

        return Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * 加 年
     */
    public static LocalDateTime plusYears(final LocalDateTime dateTime, final long years) {
        return dateTime.plusYears(years).atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

    /**
     * 加 月
     */
    public static LocalDateTime plusMonths(final LocalDateTime dateTime, final long months) {
        return dateTime.plusMonths(months).atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

    /**
     * 加 月
     */
    public static LocalDate plusMonths(final LocalDate localDate, final long months) {
        return localDate.plusMonths(months);
    }


    /**
     * 加 周
     */
    public static LocalDateTime plusWeeks(final LocalDateTime dateTime, final long weeks) {
        return dateTime.plusWeeks(weeks).atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

    /**
     * 加 天
     */
    public static LocalDateTime plusDays(final LocalDateTime dateTime, final long days) {
        return dateTime.plusDays(days).atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

    /**
     * 加 秒
     */
    public static LocalDateTime plusSeconds(final LocalDateTime dateTime, final long seconds) {
        return dateTime.plusSeconds(seconds).atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

    /**
     * 加 分
     */
    public static LocalDateTime plusMinutes(final LocalDateTime dateTime, final long minutes) {
        return dateTime.plusMinutes(minutes).atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

    /**
     * 减 年
     */
    public static LocalDateTime minusYears(final LocalDateTime dateTime, final long years) {
        return dateTime.minusYears(years).atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

    /**
     * 减 月
     */
    public static LocalDateTime minusMonths(final LocalDateTime dateTime, final long months) {
        return dateTime.minusMonths(months).atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

    /**
     * 减 月
     */
    public static LocalDate minusMonths(final LocalDate localDate, final long months) {
        return localDate.minusMonths(months);
    }

    /**
     * 减 周
     */
    public static LocalDateTime minusWeeks(final LocalDateTime dateTime, final long weeks) {
        return dateTime.minusWeeks(weeks).atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

    /**
     * 减 天
     */
    public static LocalDateTime minusDays(final LocalDateTime dateTime, final long days) {
        return dateTime.minusDays(days).atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

    /**
     * 减 时
     */
    public static LocalDateTime minusHours(final LocalDateTime dateTime, final long hours) {
        return dateTime.minusHours(hours).atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

    /**
     * 减 分
     */
    public static LocalDateTime minusMinutes(final LocalDateTime dateTime, final long minutes) {
        return dateTime.minusMinutes(minutes).atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

    /**
     * 减 秒
     */
    public static LocalDateTime minusSeconds(final LocalDateTime dateTime, final long seconds) {
        return dateTime.minusSeconds(seconds).atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

    public static void main(String[] args) {
        System.out.println(DateUtils.dateTime());

        System.out.println(DateUtils.parse("2019-08-08 23:30:00", "yyyy-MM-dd HH:mm:ss"));


    }
}

经纬度计算工具

public class LatitudeLongitudeUtil {

    private static final double EARTH_RADIUS = 6378137;

    private static final double RAD = Math.PI / 180.0;

    public static double[] getAround(double lat, double lon, int raidus) {

        Double latitude = lat;
        Double longitude = lon;

        Double degree = (24901 * 1609) / 360.0;

        Double radiusLat = (1 / degree) * (double) raidus;
        double minLat = latitude - radiusLat;
        double maxLat = latitude + radiusLat;

        Double mpdLng = degree * Math.cos(latitude * (Math.PI / 180));

        Double radiusLng = (1 / mpdLng) * (double) raidus;
        double minLng = longitude - radiusLng;
        double maxLng = longitude + radiusLng;

        return new double[]{minLat, minLng, maxLat, maxLng};
    }


    /**
     * 根据两点间经纬度坐标(double值),计算两点间距离,单位为米
     */
    public static double getDistance(double lng1, double lat1, double lng2, double lat2) {
        double radLat1 = lat1 * RAD;
        double radLat2 = lat2 * RAD;
        double a = radLat1 - radLat2;
        double b = (lng1 - lng2) * RAD;
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
                Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        return Math.round(s * 10000) / (double) 10000;
    }
}

权限缓存

public class PermissionMap {

    private static final Map<String, List<String>> PERMISSION = new ConcurrentHashMap<>();

    public static void put(String key, List<String> value) {
        getPermission().put(key, value);
    }

    public static List<String> get(String key) {
        return getPermission().get(key);
    }

    public static boolean contains(String sysCode, String value) {
        return getPermission().get(sysCode).contains(value);
    }

    private static Map<String, List<String>> getPermission() {
        return PermissionMap.PERMISSION;
    }


    public static void clear() {
        getPermission().clear();
    }
}

发送短信工具类

public class SmsUtil {

    /**
     * 发送短信对接服务
     *
     * @param phone      手机号
     * @param smsContent 发送短信的内容
     */
    public static void send(String phone, String smsContent) {
    }
}

系统变量存储和JVM缓存

public class SysConfigMap {

    private static final Map<String, String> CACHE = new ConcurrentHashMap<>();

    /**
     * 添加到JVM 中
     *
     * @param key   标识 key
     * @param value 存储的值 value
     */
    public static void put(String key, String value) {
        getCache().put(key, value);
    }


    /**
     * 从JVM中获取值
     *
     * @param key 标识 key
     */
    public static String get(String key) {
        return getCache().get(key);
    }


    public static Map<String, String> getCache() {
        return SysConfigMap.CACHE;
    }

}

验证码生成器

public class VerifyCodeUtils {
    /**
     * 图片的宽度
     */
    private int width = 120;
    /**
     * 图片的高度
     */
    private int height = 40;
    /**
     * 验证码字符个数
     */
    private int codeCount = 4;
    /**
     * 验证码
     */
    private String code = null;
    /**
     * 验证码图片Buffer
     */
    private BufferedImage buffImg = null;

    private char[] codeSequence = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'M', 'N', 'P', 'Q', 'R',
            'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9'};
    /**
     * 生成随机数
     */
    private Random random = new Random();

    public VerifyCodeUtils() {
        this.createCode();
    }

    /**
     * @param width  图片宽
     * @param height 图片高
     */
    public VerifyCodeUtils(int width, int height) {
        this.width = width;
        this.height = height;
        this.createCode();
    }

    /**
     * @param width     图片宽
     * @param height    图片高
     * @param codeCount 字符个数
     */
    public VerifyCodeUtils(int width, int height, int codeCount) {
        this.width = width;
        this.height = height;
        this.codeCount = codeCount;
        this.createCode();
    }

    public void createCode() {
        int codeX = 0;
        int fontHeight = 0;
        // 字体的高度
        fontHeight = height - 5;
        // 每个字符的宽度
        codeX = width / (codeCount + 3);

        // 图像buffer
        buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = buffImg.createGraphics();

        // 将图像填充为白色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);

        // 创建字体
        ImgFontByte imgFont = new ImgFontByte();
        Font font = imgFont.getFont(fontHeight);
        g.setFont(font);

        StringBuffer randomCode = new StringBuffer();
        // 随机产生验证码字符
        for (int i = 0; i < codeCount; i++) {
            String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
            // 设置字体颜色
            g.setColor(getRandomColor());
            // 设置字体位置
            g.drawString(strRand, (i + 1) * codeX, getRandomNumber(height / 2) + 25);
            randomCode.append(strRand);
        }
        code = randomCode.toString();
    }

    /**
     * 获取随机颜色
     */
    private Color getRandomColor() {
        int r = getRandomNumber(255);
        int g = getRandomNumber(255);
        int b = getRandomNumber(255);
        return new Color(r, g, b);
    }

    /**
     * 获取随机数
     */
    private int getRandomNumber(int number) {
        return random.nextInt(number);
    }

    public void write(String path) throws IOException {
        OutputStream out = new FileOutputStream(path);
        this.write(out);
        out.flush();
        out.close();
    }

    public void write(OutputStream sos) throws IOException {
        ImageIO.write(buffImg, "png", sos);
    }

    public BufferedImage getBuffImg() {
        return buffImg;
    }

    public String getCode() {
        return code;
    }

    /**
     * 字体样式类
     */
    static class ImgFontByte {

        public Font getFont(int fontHeight) {

            return new Font("Arial", Font.PLAIN, fontHeight);
        }

        private byte[] hex2byte(String str) {
            if (str == null || str.isEmpty()) {
                return null;
            }
            str = str.trim();
            int len = str.length();
            byte[] b = new byte[len / 2];
            try {
                for (int i = 0; i < str.length(); i += 2) {
                    b[i / 2] = (byte) Integer.decode("0x" + str.substring(i, i + 2)).intValue();
                }
                return b;
            } catch (Exception e) {
                return null;
            }
        }

    }
}

public final class VerifyCodeUtils{
	// 使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符23456789ABCDEFGHJKLMNPQRSTUVWXYZ
	public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
	private static Random random;

	static{
		try{
			random = SecureRandom.getInstanceStrong();
		}catch(NoSuchAlgorithmException e){
			e.printStackTrace();
		}
	}

	//使用系统默认字符源生成验证码
	public static String generateVerifyCode(int verifySize) {
		return generateVerifyCode(verifySize, VERIFY_CODES);
	}
	//使用指定源生成验证码
	public static String generateVerifyCode(int verifySize,String sources){
		if (sources == null || sources.length() == 0) {
			sources = VERIFY_CODES;
		}
		int codesLen = sources.length();
		Random rand = new Random(System.currentTimeMillis());
		StringBuilder verifyCode = new StringBuilder(verifySize);
		for (int i = 0; i < verifySize; i++) {
			verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
		}
		return verifyCode.toString();
	}
	/**
	 * 生成随机验证码文件,并返回验证码值
	 * 
	 * @param w
	 * @param h
	 * @param outputFile
	 * @param verifySize
	 * @return
	 * @throws IOException
	 */
	public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException {
		String verifyCode = generateVerifyCode(verifySize);
		outputImage(w, h, outputFile, verifyCode);
		return verifyCode;
	}

	/**
	 * 输出随机验证码图片流,并返回验证码值
	 * 
	 * @param w
	 * @param h
	 * @param os
	 * @param verifySize
	 * @return
	 * @throws IOException
	 */
	public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException {
		String verifyCode = generateVerifyCode(verifySize);
		outputImage(w, h, os, verifyCode);
		return verifyCode;
	}

	/**
	 * 生成指定验证码图像文件
	 * 
	 * @param w
	 * @param h
	 * @param outputFile
	 * @param code
	 * @throws IOException
	 */
	public static void outputImage(int w, int h, File outputFile, String code) throws IOException {
		if (outputFile == null) {
			return;
		}
		File dir = outputFile.getParentFile();
		if (!dir.exists()) {
			dir.mkdirs();
		}
		try {
			outputFile.createNewFile();
			FileOutputStream fos = new FileOutputStream(outputFile);
			outputImage(w, h, fos, code);
			fos.close();
		} catch (IOException e) {
			throw e;
		}
	}

	/**
	 * 输出指定验证码图片流
	 * 
	 * @param w
	 * @param h
	 * @param os
	 * @param code
	 * @throws IOException
	 */
	public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {
		int verifySize = code.length();
		BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
		Random rand = new Random();
		Graphics2D g2 = image.createGraphics();
		g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		Color[] colors = new Color[5];
		Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN, Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA,
				Color.ORANGE, Color.PINK, Color.YELLOW };
		float[] fractions = new float[colors.length];
		for (int i = 0; i < colors.length; i++) {
			colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
			fractions[i] = rand.nextFloat();
		}
		Arrays.sort(fractions);

		g2.setColor(Color.GRAY);// 设置边框色
		g2.fillRect(0, 0, w, h);

		Color c = getRandColor(200, 250);
		g2.setColor(c);// 设置背景色
		g2.fillRect(0, 2, w, h - 4);

		// 绘制干扰线
		Random random = new Random();
		g2.setColor(getRandColor(160, 200));// 设置线条的颜色
		for (int i = 0; i < 20; i++) {
			int x = random.nextInt(w - 1);
			int y = random.nextInt(h - 1);
			int xl = random.nextInt(6) + 1;
			int yl = random.nextInt(12) + 1;
			g2.drawLine(x, y, x + xl + 40, y + yl + 20);
		}

		// 添加噪点
		float yawpRate = 0.05f;// 噪声率
		int area = (int) (yawpRate * w * h);
		for (int i = 0; i < area; i++) {
			int x = random.nextInt(w);
			int y = random.nextInt(h);
			int rgb = getRandomIntColor();
			image.setRGB(x, y, rgb);
		}

		shear(g2, w, h, c);// 使图片扭曲

		g2.setColor(getRandColor(100, 160));
		int fontSize = h - 4;
		Font font = new Font("Algerian", Font.ITALIC, fontSize);
		g2.setFont(font);
		char[] chars = code.toCharArray();
		for (int i = 0; i < verifySize; i++) {
			AffineTransform affine = new AffineTransform();
			affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1),
					(w / verifySize) * i + fontSize / 2, h / 2);
			g2.setTransform(affine);
			g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
		}

		g2.dispose();
		ImageIO.write(image, "jpg", os);
	}

	private static Color getRandColor(int fc, int bc) {
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}

	private static int getRandomIntColor() {
		int[] rgb = getRandomRgb();
		int color = 0;
		for (int c : rgb) {
			color = color << 8;
			color = color | c;
		}
		return color;
	}

	private static int[] getRandomRgb() {
		int[] rgb = new int[3];
		for (int i = 0; i < 3; i++) {
			rgb[i] = random.nextInt(255);
		}
		return rgb;
	}

	private static void shear(Graphics g, int w1, int h1, Color color) {
		shearX(g, w1, h1, color);
		shearY(g, w1, h1, color);
	}

	private static void shearX(Graphics g, int w1, int h1, Color color) {

		int period = random.nextInt(2);

		boolean borderGap = true;
		int frames = 1;
		int phase = random.nextInt(2);

		for (int i = 0; i < h1; i++) {
			double d = (double) (period >> 1)
					* Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
			g.copyArea(0, i, w1, 1, (int) d, 0);
			if (borderGap) {
				g.setColor(color);
				g.drawLine((int) d, i, 0, i);
				g.drawLine((int) d + w1, i, w1, i);
			}
		}

	}

	private static void shearY(Graphics g, int w1, int h1, Color color) {

		int period = random.nextInt(40) + 10; // 50;

		boolean borderGap = true;
		int frames = 20;
		int phase = 7;
		for (int i = 0; i < w1; i++) {
			double d = (double) (period >> 1)
					* Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
			g.copyArea(i, 0, 1, h1, 0, (int) d);
			if (borderGap) {
				g.setColor(color);
				g.drawLine(i, (int) d, i, 0);
				g.drawLine(i, (int) d + h1, i, h1);
			}
		}
	}
}

根据图片地址转换为base64编码字符串

public class ImgBase64{
	public static String getImageBase64(String imgFile){
		ImputStream inputStream = null;
		byte[] data = null;
		try{
			inputStream = new FileInputStream(imgFile);
			data = new byte[inputStream.available()];
			inputStream.read(data);
			inputStream.close();
		}catch(IOException e){
			e.printStackTrace();
		}
		
		//返回BASE64编码过的字节数组字符串
		BASE64Encoder encoder = new BASE64Encoder();
		String imgStr = encoder.encode(data);
		retrun "data:image/jpeg;base64," + imgStr;
	}
}

HttpContextUtils工具

public class HttpContextUtils{
	
	//获取HttpServietRequest请求
	public static HttpServletRequest(){
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes().getRequest());
	}

	//通过上面方法返回的HttpServletRequest,获取主机名
	public static String getDomain(){
		HttpServletRequest request = getHttpServletRequest();
		StringBuffer url = request.getRequestURL();
		return url.delete(url.length() - request.getRequestURI().length(),url.length()).toString();
	}

	public static String getOrigin(){
		HttpServletRequest request = getHttpServletRequest();
		return request.getHealder("Origin");
	}
}

获取IP

public class IpHelper{
	
	private static final String UNKNOWN = "unknown";

	public static String getIpAddr(){
		HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
		if(request == null){
			return null;
		}
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        String[] ips = ip.split(",");
        return ips[0].trim();
	}
}
/**
	servlet-api依赖
	spring-core
*/
public class GetIp{

	public static String getIp(HttpServletRequest request){
		String ip = request.getHeader("X-Forwarded-For");
		if(!StringUtils.getEmpty(ip) && "unKnown".wqualsIgnoreCase(ip)){
			//多次反向代理会有多个ip,第一个ip才是真实的ip
			int index = ip.indexOf(",");
			if(index!=-1){
				return ip.substring(0,index);
			}else{
				return ip;
			}
		}
		ip = request.getHeader("X-Real-IP");
		if(!StringUtils.isEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
			return ip;
		}
		return request.getRemoteAddr();
	}
}

SpringContextUtils工具

@Component
public class SpringContextUtils implements ApplicationContextAware{
	
	public static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException{
		SpringContextUtils.applicationContext = applicationContext;
	}

	public static Object getBean(String name){
		return applicationContext.getBean(name);
	}

	public static<T> T getBean(String name,Class<T> requiredType){
		return applicationContext.getBean(name,requiredType);
	}

	public static boolean containsBean(String name){
		return applicationContext.containsBean(name);
	}

	public static boolean isSingleton(String name){
		return applicationContext.isSingleton(name);
	}

	public static Class<? extends Object> getType(String name){
		return applicationContext.getType(name);
	}
}

RedisUtil工具

@Slf4j
public class RedisUtil{
	private static RedisTemplate<String,Object> redisTemplate = SpringContextUtils.getBean("redisTemplate", RedisTemplate.class);
	public static final StringRedisTemplate STRING_REDIS_TEMPLATE=SpringContextUtils.getBean("stringRedisTemplate",StringRedisTemplate.class);

	//指定缓存失效时间
	public static boolean expire(String key,long time){
		try{
			if(time > 0){
				redisTemplate.expire(key,time,TimeUnit.SECONDS);
			}
			return true;
		}catch(Exception e){
			log.error("设置redis指定key失效时间错误:", e);
			return false;
		}
	}

	//根据key获取过期时间
	public static Long getExpire(Sring key){
		return redisTemplate.getExpire(key,TimeUnit.SECONDS);
	}
	
	//判断key是否存在
	public static Boolean hasKey(String key){
		try{
			return redisTemplate.hasKey(key);
		}catch(Exception e){
			log.error("redis判断key是否存在错误:", e);
			return false;
		}
	}

	//删除缓存
	@SuppressWarnings("unchecked")
	public static void del(String... key){
		if(key != null && key.length > 0){
			if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(Arrays.asList(key));
            }
		}
	}

	//普通缓存获取
	@SuppressWarnings("unchecked")
    public static <T> T get(String key) {
        return key == null ? null : (T) redisTemplate.opsForValue().get(key);
    }

	//普通缓存放入
	public static boolean set(String key,Object value){
		try{
			redisTemplate.opsForValue().set(key,value);
			return true;
		}catch(Exception e){
			log.error("设置redis缓存错误:", e);
            return false;
		}
	}

	//普通缓存放入,并设置时间
	public static boolean set(String key,Object value,long time){
		try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
	}

	//递增,value必需为int类型,否则报错
	public static Long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return STRING_REDIS_TEMPLATE.opsForValue().increment(key, delta);
    }

	//递减
	public static Long decr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递减因子必须大于0");
        }
        return STRING_REDIS_TEMPLATE.opsForValue().increment(key, -delta);
    }
}

AES可逆加密

对原始数据进行AES加密后,再进行Base64编码转化

public class Jiami{
	//加密用的Key 可以用26个字母和数字组成 此处使用AES-128-CBC加密模式,key需要为16位。 
	private String sKey = "abcdef0123456789"
	private String ivParameter = "0123456789abcdef";
	private static Jiami instance = null;

	private Jiami() {

	}
	public static Jiami getInstance() {
		if (instance == null)
			instance = new Jiami();
		return instance;
	}

	//加密
	public String encrypt(String sSrc){
		String result = "";
		try {
			Cipher cipher;
			cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			byte[] raw = sKey.getBytes();
			SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
			IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());// 使用CBC模式,需要一个向量iv,可增加加密算法的强度
			cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
			byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
			result = new BASE64Encoder().encode(encrypted);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		// 此处使用BASE64做转码。
		return result;
	}
	// 解密
	public String decrypt(String sSrc) {
		try {
			byte[] raw = sKey.getBytes("ASCII");
			SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
			cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
			byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);// 先用base64解密
			byte[] original = cipher.doFinal(encrypted1);
			String originalString = new String(original, "utf-8");
			return originalString;
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}
	public static void main(String[] args) {
		// 需要加密的字串
		String cSrc = "2";
		System.out.println(cSrc + "长度为" + cSrc.length());
		// 加密
		long lStart = System.currentTimeMillis();
		String enString = Jiami.getInstance().encrypt(cSrc);
		System.out.println("加密后的字串是:" + enString + "长度为" + enString.length());
		
		long lUseTime = System.currentTimeMillis() - lStart;
		System.out.println("加密耗时:" + lUseTime + "毫秒");
		// 解密
		lStart = System.currentTimeMillis();
		String DeString = Jiami.getInstance().decrypt(enString);
		System.out.println("解密后的字串是:" + DeString);
		lUseTime = System.currentTimeMillis() - lStart;
		System.out.println("解密耗时:" + lUseTime + "毫秒");
	}
}

MD5加密

/**
 * 将传入的字符串进行加密,并返回加密后的字符串。
 */
public class MD5 {

	public static String md5(String data) {
		try {
			byte[] md5 = md5(data.getBytes("utf-8"));
			return toHexString(md5);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}

	public static byte[] md5(byte[] data) {
		try {
			MessageDigest md = MessageDigest.getInstance("md5");
			md.update(data);
			return md.digest();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return new byte[] {};
	}

	public static String toHexString(byte[] md5) {
		StringBuilder buf = new StringBuilder();
		for (byte b : md5) {
			buf.append(leftPad(Integer.toHexString(b & 0xff), '0', 2));
		}
		return buf.toString();
	}

	public static String leftPad(String hex, char c, int size) {
		char[] cs = new char[size];
		Arrays.fill(cs, c);
		System.arraycopy(hex.toCharArray(), 0, cs, 
				cs.length - hex.length(), hex.length());
		return new String(cs);
	}

	public static void main(String[] args) {
		System.out.println(md5("123456"));
	}

}

MD5

public final class MD5{
	
	public static String encrypt(String strSrc){
		try{
			char hexChars[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
			byte[] bytes = strSrc.getBytes();
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(bytes);
			bytes = md.digest();
			int j = bytes.length;
			char[] chars = new char[j*2];
			int k = 0;
			for(int i = 0;i < bytes.length;i++){
				byte b = bytes[i];
				chars[k++] = hexChars[b >>> 4 & 0xf];
				chars[k++] = hexChars[b & 0xf];
			}
			return new String(chars);
		}catch(NoSuchAlgorithmException e){
			e.printStackTrace();
			throw new RuntimeException("MD5加密出错!!" + e);
		}
	}

	//测试
	public static void main(String[] args){
		System.out.println(MD5.encrpt("111111"));
	}
}
/**
 * MD5加密工具
 *
 */
public class MD5Util {

    private static final String SALT = "tamboo";

    public static String encode(String password) {
        password = password + SALT;
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        char[] charArray = password.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }

            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    public static void main(String[] args) {
        System.out.println(MD5Util.encode("abel"));


    }
}

ThreadLocal

@Slf4j
public class SmartRequestUtil{
	
	private static final ThreadLocal<RequestUser> requeestThreadLocal = new ThreadLocal<>();

	public static void setRequestUser(RequestUser requestUser){
		requestThreadLocal.set(requestUser);
	}
	public static RequestUser getRequestUser(){
		return requestThreadLocal.get();
	}

	public static Long getRequestUserId(){
		RequestUser requestUser = getRequestUser();
		return null == requestUser ? null:requestUser.getUserId();
	}

	public static void remove(){
		requestThreadLocal.remove();
	}
}

======================================

Hutool工具

//获取文件扩展名(后缀名),扩展名不带“.”
FileUtil.extName(file.getOriginalFilename());

//格式化日期输出 //结果 2017/03/01       String format = DateUtil.format(date, "yyyy/MM/dd");
//生成的是不带-的字符串,类似于:b17f24ff026d40949c85a24f4f375d42     String simpleUUID = IdUtil.simpleUUID();
DateUtil.format(new Date(), NORM_MONTH_PATTERN)+ IdUtil.simpleUUID() + "." + extName;

//遍历集合中每个Bean,复制其属性后加入一个新的List中
BeanUtil.copyToList(userAddrs, UserAddrDto.class)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值