This commit is contained in:
Looly 2023-04-22 02:36:32 +08:00
parent 7387150f1a
commit 16e05bf9f5
108 changed files with 1244 additions and 857 deletions

View File

@ -14,7 +14,7 @@ package org.dromara.hutool.core.annotation;
import org.dromara.hutool.core.array.ArrayUtil;
import org.dromara.hutool.core.classloader.ClassLoaderUtil;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.func.LambdaInfo;
import org.dromara.hutool.core.func.LambdaUtil;
import org.dromara.hutool.core.func.SerFunction;
@ -181,9 +181,9 @@ public class AnnotationUtil {
* @param annotationEle {@link AnnotatedElement}可以是ClassMethodFieldConstructorReflectPermission
* @param annotationType 注解类型
* @return 注解对象
* @throws UtilException 调用注解中的方法时执行异常
* @throws HutoolException 调用注解中的方法时执行异常
*/
public static <T> T getAnnotationValue(final AnnotatedElement annotationEle, final Class<? extends Annotation> annotationType) throws UtilException {
public static <T> T getAnnotationValue(final AnnotatedElement annotationEle, final Class<? extends Annotation> annotationType) throws HutoolException {
return getAnnotationValue(annotationEle, annotationType, "value");
}
@ -196,7 +196,7 @@ public class AnnotationUtil {
* @param annotationEle {@link AnnotatedElement}可以是ClassMethodFieldConstructorReflectPermission
* @param propertyName 属性名例如注解中定义了name()方法 此处传入name
* @return 注解对象
* @throws UtilException 调用注解中的方法时执行异常
* @throws HutoolException 调用注解中的方法时执行异常
*/
public static <A extends Annotation, R> R getAnnotationValue(final AnnotatedElement annotationEle, final SerFunction<A, R> propertyName) {
if(propertyName == null) {
@ -218,9 +218,9 @@ public class AnnotationUtil {
* @param annotationType 注解类型
* @param propertyName 属性名例如注解中定义了name()方法 此处传入name
* @return 注解对象
* @throws UtilException 调用注解中的方法时执行异常
* @throws HutoolException 调用注解中的方法时执行异常
*/
public static <T> T getAnnotationValue(final AnnotatedElement annotationEle, final Class<? extends Annotation> annotationType, final String propertyName) throws UtilException {
public static <T> T getAnnotationValue(final AnnotatedElement annotationEle, final Class<? extends Annotation> annotationType, final String propertyName) throws HutoolException {
final Annotation annotation = getAnnotation(annotationEle, annotationType);
if (null == annotation) {
return null;
@ -240,9 +240,9 @@ public class AnnotationUtil {
* @param annotationEle {@link AnnotatedElement}可以是ClassMethodFieldConstructorReflectPermission
* @param annotationType 注解类型
* @return 注解对象
* @throws UtilException 调用注解中的方法时执行异常
* @throws HutoolException 调用注解中的方法时执行异常
*/
public static Map<String, Object> getAnnotationValueMap(final AnnotatedElement annotationEle, final Class<? extends Annotation> annotationType) throws UtilException {
public static Map<String, Object> getAnnotationValueMap(final AnnotatedElement annotationEle, final Class<? extends Annotation> annotationType) throws HutoolException {
final Annotation annotation = getAnnotation(annotationEle, annotationType);
if (null == annotation) {
return null;

View File

@ -18,7 +18,7 @@ import org.dromara.hutool.core.collection.set.SetUtil;
import org.dromara.hutool.core.collection.set.UniqueKeySet;
import org.dromara.hutool.core.comparator.CompareUtil;
import org.dromara.hutool.core.convert.Convert;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.map.MapUtil;
import org.dromara.hutool.core.text.StrJoiner;
@ -1124,7 +1124,7 @@ public class ArrayUtil extends PrimitiveArrayUtil {
*
* @param obj 对象可以是对象数组或者基本类型数组
* @return 包装类型数组或对象数组
* @throws UtilException 对象为非数组
* @throws HutoolException 对象为非数组
*/
public static Object[] wrap(final Object obj) {
if (null == obj) {
@ -1154,10 +1154,10 @@ public class ArrayUtil extends PrimitiveArrayUtil {
return (Object[]) obj;
}
} catch (final Exception e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}
throw new UtilException(StrUtil.format("[{}] is not Array!", obj.getClass()));
throw new HutoolException(StrUtil.format("[{}] is not Array!", obj.getClass()));
}
/**

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.bean;
import org.dromara.hutool.core.exceptions.CloneRuntimeException;
import org.dromara.hutool.core.exceptions.CloneException;
import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.reflect.ClassUtil;
import org.dromara.hutool.core.reflect.ConstructorUtil;
@ -242,7 +242,7 @@ public class DynaBean implements Cloneable, Serializable {
try {
return (DynaBean) super.clone();
} catch (final CloneNotSupportedException e) {
throw new CloneRuntimeException(e);
throw new CloneException(e);
}
}
}

View File

@ -16,10 +16,7 @@ import org.dromara.hutool.core.annotation.AnnotationUtil;
import org.dromara.hutool.core.annotation.PropIgnore;
import org.dromara.hutool.core.convert.Convert;
import org.dromara.hutool.core.func.LambdaUtil;
import org.dromara.hutool.core.reflect.FieldUtil;
import org.dromara.hutool.core.reflect.ModifierUtil;
import org.dromara.hutool.core.reflect.ReflectUtil;
import org.dromara.hutool.core.reflect.TypeUtil;
import org.dromara.hutool.core.reflect.*;
import java.beans.Transient;
import java.lang.reflect.Field;
@ -237,8 +234,7 @@ public class PropDesc {
*/
public PropDesc setValue(final Object bean, final Object value) {
if (null != this.setter) {
//MethodUtil.invoke(bean, this.setter, value);
LambdaUtil.buildSetter(this.setter).accept(bean, value);
MethodUtil.invoke(bean, this.setter, value);
} else if (ModifierUtil.isPublic(this.field)) {
FieldUtil.setFieldValue(bean, this.field, value);
}

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.classloader;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.reflect.ClassDescUtil;
import java.io.File;
@ -108,9 +108,9 @@ public class ClassLoaderUtil {
* @param <T> 目标类的类型
* @param name 类名
* @return 类名对应的类
* @throws UtilException 包装{@link ClassNotFoundException}没有类名对应的类时抛出此异常
* @throws HutoolException 包装{@link ClassNotFoundException}没有类名对应的类时抛出此异常
*/
public static <T> Class<T> loadClass(final String name) throws UtilException {
public static <T> Class<T> loadClass(final String name) throws HutoolException {
return loadClass(name, true);
}
@ -128,9 +128,9 @@ public class ClassLoaderUtil {
* @param name 类名
* @param isInitialized 是否初始化类调用static模块内容和初始化static属性
* @return 类名对应的类
* @throws UtilException 包装{@link ClassNotFoundException}没有类名对应的类时抛出此异常
* @throws HutoolException 包装{@link ClassNotFoundException}没有类名对应的类时抛出此异常
*/
public static <T> Class<T> loadClass(final String name, final boolean isInitialized) throws UtilException {
public static <T> Class<T> loadClass(final String name, final boolean isInitialized) throws HutoolException {
return loadClass(name, isInitialized, null);
}
@ -151,10 +151,10 @@ public class ClassLoaderUtil {
* @param classLoader {@link ClassLoader}{@code null} 则使用{@link #getClassLoader()}获取
* @param isInitialized 是否初始化类调用static模块内容和初始化static属性
* @return 类名对应的类
* @throws UtilException 包装{@link ClassNotFoundException}没有类名对应的类时抛出此异常
* @throws HutoolException 包装{@link ClassNotFoundException}没有类名对应的类时抛出此异常
*/
@SuppressWarnings("unchecked")
public static <T> Class<T> loadClass(final String name, final boolean isInitialized, final ClassLoader classLoader) throws UtilException {
public static <T> Class<T> loadClass(final String name, final boolean isInitialized, final ClassLoader classLoader) throws HutoolException {
return (Class<T>) ClassDescUtil.nameToClass(name, isInitialized, classLoader);
}
@ -170,7 +170,7 @@ public class ClassLoaderUtil {
try {
return getJarClassLoader(jarOrDir).loadClass(name);
} catch (final ClassNotFoundException e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.classloader;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.io.file.FileUtil;
import org.dromara.hutool.core.net.url.URLUtil;
import org.dromara.hutool.core.reflect.MethodUtil;
@ -61,9 +61,9 @@ public class JarClassLoader extends URLClassLoader {
*
* @param loader {@link URLClassLoader}
* @param jarFile 被加载的jar
* @throws UtilException IO异常包装和执行异常
* @throws HutoolException IO异常包装和执行异常
*/
public static void loadJar(final URLClassLoader loader, final File jarFile) throws UtilException {
public static void loadJar(final URLClassLoader loader, final File jarFile) throws HutoolException {
try {
final Method method = MethodUtil.getMethod(URLClassLoader.class, "addURL", URL.class);
if (null != method) {
@ -73,7 +73,7 @@ public class JarClassLoader extends URLClassLoader {
}
}
} catch (final IOException e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}

View File

@ -13,7 +13,7 @@
package org.dromara.hutool.core.codec;
import org.dromara.hutool.core.codec.binary.Base16Codec;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.util.ByteUtil;
import org.dromara.hutool.core.util.CharUtil;
@ -201,7 +201,7 @@ public class HexUtil {
*
* @param hexData 十六进制字符串
* @return byte[]
* @throws UtilException 如果源十六进制字符数组是一个奇怪的长度将抛出运行时异常
* @throws HutoolException 如果源十六进制字符数组是一个奇怪的长度将抛出运行时异常
* @since 5.6.6
*/
public static byte[] decodeHex(final CharSequence hexData) {

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.codec;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.text.split.SplitUtil;
@ -44,9 +44,9 @@ public class PunyCode {
*
* @param domain 域名
* @return 编码后的域名
* @throws UtilException 计算异常
* @throws HutoolException 计算异常
*/
public static String encodeDomain(final String domain) throws UtilException {
public static String encodeDomain(final String domain) throws HutoolException {
Assert.notNull(domain, "domain must not be null!");
final List<String> split = SplitUtil.split(domain, StrUtil.DOT);
final StringBuilder result = new StringBuilder(domain.length() * 4);
@ -65,9 +65,9 @@ public class PunyCode {
*
* @param input 字符串
* @return PunyCode字符串
* @throws UtilException 计算异常
* @throws HutoolException 计算异常
*/
public static String encode(final CharSequence input) throws UtilException {
public static String encode(final CharSequence input) throws HutoolException {
return encode(input, false);
}
@ -77,9 +77,9 @@ public class PunyCode {
* @param input 字符串
* @param withPrefix 是否包含 "xn--"前缀
* @return PunyCode字符串
* @throws UtilException 计算异常
* @throws HutoolException 计算异常
*/
public static String encode(final CharSequence input, final boolean withPrefix) throws UtilException {
public static String encode(final CharSequence input, final boolean withPrefix) throws HutoolException {
Assert.notNull(input, "input must not be null!");
int n = INITIAL_N;
int delta = 0;
@ -114,7 +114,7 @@ public class PunyCode {
}
}
if (m - n > (Integer.MAX_VALUE - delta) / (h + 1)) {
throw new UtilException("OVERFLOW");
throw new HutoolException("OVERFLOW");
}
delta = delta + (m - n) * (h + 1);
n = m;
@ -123,7 +123,7 @@ public class PunyCode {
if (c < n) {
delta++;
if (0 == delta) {
throw new UtilException("OVERFLOW");
throw new HutoolException("OVERFLOW");
}
}
if (c == n) {
@ -164,9 +164,9 @@ public class PunyCode {
*
* @param domain 域名
* @return 解码后的域名
* @throws UtilException 计算异常
* @throws HutoolException 计算异常
*/
public static String decodeDomain(final String domain) throws UtilException {
public static String decodeDomain(final String domain) throws HutoolException {
Assert.notNull(domain, "domain must not be null!");
final List<String> split = SplitUtil.split(domain, StrUtil.DOT);
final StringBuilder result = new StringBuilder(domain.length() / 4 + 1);
@ -185,9 +185,9 @@ public class PunyCode {
*
* @param input PunyCode
* @return 字符串
* @throws UtilException 计算异常
* @throws HutoolException 计算异常
*/
public static String decode(String input) throws UtilException {
public static String decode(String input) throws HutoolException {
Assert.notNull(input, "input must not be null!");
input = StrUtil.removePrefixIgnoreCase(input, PUNY_CODE_PREFIX);
@ -213,12 +213,12 @@ public class PunyCode {
int w = 1;
for (int k = BASE; ; k += BASE) {
if (d == length) {
throw new UtilException("BAD_INPUT");
throw new HutoolException("BAD_INPUT");
}
final int c = input.charAt(d++);
final int digit = codepoint2digit(c);
if (digit > (Integer.MAX_VALUE - i) / w) {
throw new UtilException("OVERFLOW");
throw new HutoolException("OVERFLOW");
}
i = i + digit * w;
final int t;
@ -236,7 +236,7 @@ public class PunyCode {
}
bias = adapt(i - oldi, output.length() + 1, oldi == 0);
if (i / (output.length() + 1) > Integer.MAX_VALUE - n) {
throw new UtilException("OVERFLOW");
throw new HutoolException("OVERFLOW");
}
n = n + i / (output.length() + 1);
i = i % (output.length() + 1);
@ -280,9 +280,9 @@ public class PunyCode {
*
* @param d 输入字符
* @return 转换后的字符
* @throws UtilException 无效字符
* @throws HutoolException 无效字符
*/
private static int digit2codepoint(final int d) throws UtilException {
private static int digit2codepoint(final int d) throws HutoolException {
Assert.checkBetween(d, 0, 35);
if (d < 26) {
// 0..25 : 'a'..'z'
@ -291,7 +291,7 @@ public class PunyCode {
// 26..35 : '0'..'9';
return d - 26 + '0';
} else {
throw new UtilException("BAD_INPUT");
throw new HutoolException("BAD_INPUT");
}
}
@ -309,9 +309,9 @@ public class PunyCode {
*
* @param c 输入字符
* @return 转换后的字符
* @throws UtilException 无效字符
* @throws HutoolException 无效字符
*/
private static int codepoint2digit(final int c) throws UtilException {
private static int codepoint2digit(final int c) throws HutoolException {
if (c - '0' < 10) {
// '0'..'9' : 26..35
return c - '0' + 26;
@ -319,7 +319,7 @@ public class PunyCode {
// 'a'..'z' : 0..25
return c - 'a';
} else {
throw new UtilException("BAD_INPUT");
throw new HutoolException("BAD_INPUT");
}
}
}

View File

@ -14,7 +14,7 @@ package org.dromara.hutool.core.codec.binary;
import org.dromara.hutool.core.codec.Decoder;
import org.dromara.hutool.core.codec.Encoder;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.text.StrUtil;
/**
@ -137,12 +137,12 @@ public class Base16Codec implements Encoder<byte[], char[]>, Decoder<CharSequenc
* @param ch 十六进制char
* @param index 十六进制字符在字符数组中的位置
* @return 一个整数
* @throws UtilException 当ch不是一个合法的十六进制字符时抛出运行时异常
* @throws HutoolException 当ch不是一个合法的十六进制字符时抛出运行时异常
*/
private static int toDigit(final char ch, final int index) {
final int digit = Character.digit(ch, 16);
if (digit < 0) {
throw new UtilException("Illegal hexadecimal character {} at index {}", ch, index);
throw new HutoolException("Illegal hexadecimal character {} at index {}", ch, index);
}
return digit;
}

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.codec.binary;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.exceptions.ValidateException;
import java.security.MessageDigest;
@ -158,7 +158,7 @@ public class Base58 {
try {
return MessageDigest.getInstance("SHA-256").digest(data);
} catch (final NoSuchAlgorithmException e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}
}

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.codec.hash;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@ -55,7 +55,7 @@ public class KetamaHash implements Hash64<byte[]>, Hash32<byte[]> {
try {
md5 = MessageDigest.getInstance("MD5");
} catch (final NoSuchAlgorithmException e) {
throw new UtilException("MD5 algorithm not suooport!", e);
throw new HutoolException("MD5 algorithm not suooport!", e);
}
return md5.digest(key);
}

View File

@ -24,7 +24,7 @@ import org.dromara.hutool.core.comparator.PinyinComparator;
import org.dromara.hutool.core.comparator.PropertyComparator;
import org.dromara.hutool.core.convert.CompositeConverter;
import org.dromara.hutool.core.convert.Convert;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.func.SerBiConsumer;
import org.dromara.hutool.core.func.SerConsumer3;
@ -764,7 +764,7 @@ public class CollUtil {
if (null != superclass && collectionType != superclass) {
return create(superclass);
}
throw new UtilException(e);
throw new HutoolException(e);
}
}
return list;

View File

@ -13,7 +13,7 @@
package org.dromara.hutool.core.compress;
import org.dromara.hutool.core.collection.iter.EnumerationIter;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.io.IORuntimeException;
import org.dromara.hutool.core.io.IoUtil;
import org.dromara.hutool.core.io.file.FileNameUtil;
@ -138,9 +138,9 @@ public class ZipUtil {
*
* @param srcPath 源文件路径
* @return 打包好的压缩文件
* @throws UtilException IO异常
* @throws HutoolException IO异常
*/
public static File zip(final String srcPath) throws UtilException {
public static File zip(final String srcPath) throws HutoolException {
return zip(srcPath, DEFAULT_CHARSET);
}
@ -150,9 +150,9 @@ public class ZipUtil {
* @param srcPath 源文件路径
* @param charset 编码
* @return 打包好的压缩文件
* @throws UtilException IO异常
* @throws HutoolException IO异常
*/
public static File zip(final String srcPath, final Charset charset) throws UtilException {
public static File zip(final String srcPath, final Charset charset) throws HutoolException {
return zip(FileUtil.file(srcPath), charset);
}
@ -161,9 +161,9 @@ public class ZipUtil {
*
* @param srcFile 源文件或目录
* @return 打包好的压缩文件
* @throws UtilException IO异常
* @throws HutoolException IO异常
*/
public static File zip(final File srcFile) throws UtilException {
public static File zip(final File srcFile) throws HutoolException {
return zip(srcFile, DEFAULT_CHARSET);
}
@ -173,9 +173,9 @@ public class ZipUtil {
* @param srcFile 源文件或目录
* @param charset 编码
* @return 打包好的压缩文件
* @throws UtilException IO异常
* @throws HutoolException IO异常
*/
public static File zip(final File srcFile, final Charset charset) throws UtilException {
public static File zip(final File srcFile, final Charset charset) throws HutoolException {
final File zipFile = FileUtil.file(srcFile.getParentFile(), FileNameUtil.mainName(srcFile) + ".zip");
zip(zipFile, charset, false, srcFile);
return zipFile;
@ -188,9 +188,9 @@ public class ZipUtil {
* @param srcPath 要压缩的源文件路径如果压缩一个文件则为该文件的全路径如果压缩一个目录则为该目录的顶层目录路径
* @param zipPath 压缩文件保存的路径包括文件名注意zipPath不能是srcPath路径下的子文件夹
* @return 压缩好的Zip文件
* @throws UtilException IO异常
* @throws HutoolException IO异常
*/
public static File zip(final String srcPath, final String zipPath) throws UtilException {
public static File zip(final String srcPath, final String zipPath) throws HutoolException {
return zip(srcPath, zipPath, false);
}
@ -201,9 +201,9 @@ public class ZipUtil {
* @param zipPath 压缩文件保存的路径包括文件名注意zipPath不能是srcPath路径下的子文件夹
* @param withSrcDir 是否包含被打包目录
* @return 压缩文件
* @throws UtilException IO异常
* @throws HutoolException IO异常
*/
public static File zip(final String srcPath, final String zipPath, final boolean withSrcDir) throws UtilException {
public static File zip(final String srcPath, final String zipPath, final boolean withSrcDir) throws HutoolException {
return zip(srcPath, zipPath, DEFAULT_CHARSET, withSrcDir);
}
@ -215,9 +215,9 @@ public class ZipUtil {
* @param charset 编码
* @param withSrcDir 是否包含被打包目录
* @return 压缩文件
* @throws UtilException IO异常
* @throws HutoolException IO异常
*/
public static File zip(final String srcPath, final String zipPath, final Charset charset, final boolean withSrcDir) throws UtilException {
public static File zip(final String srcPath, final String zipPath, final Charset charset, final boolean withSrcDir) throws HutoolException {
final File srcFile = FileUtil.file(srcPath);
final File zipFile = FileUtil.file(zipPath);
zip(zipFile, charset, withSrcDir, srcFile);
@ -232,9 +232,9 @@ public class ZipUtil {
* @param withSrcDir 是否包含被打包目录只针对压缩目录有效若为false则只压缩目录下的文件或目录为true则将本目录也压缩
* @param srcFiles 要压缩的源文件或目录
* @return 压缩文件
* @throws UtilException IO异常
* @throws HutoolException IO异常
*/
public static File zip(final File zipFile, final boolean withSrcDir, final File... srcFiles) throws UtilException {
public static File zip(final File zipFile, final boolean withSrcDir, final File... srcFiles) throws HutoolException {
return zip(zipFile, DEFAULT_CHARSET, withSrcDir, srcFiles);
}
@ -246,9 +246,9 @@ public class ZipUtil {
* @param withSrcDir 是否包含被打包目录只针对压缩目录有效若为false则只压缩目录下的文件或目录为true则将本目录也压缩
* @param srcFiles 要压缩的源文件或目录如果压缩一个文件则为该文件的全路径如果压缩一个目录则为该目录的顶层目录路径
* @return 压缩文件
* @throws UtilException IO异常
* @throws HutoolException IO异常
*/
public static File zip(final File zipFile, final Charset charset, final boolean withSrcDir, final File... srcFiles) throws UtilException {
public static File zip(final File zipFile, final Charset charset, final boolean withSrcDir, final File... srcFiles) throws HutoolException {
return zip(zipFile, charset, withSrcDir, null, srcFiles);
}
@ -293,10 +293,10 @@ public class ZipUtil {
* @param path 流数据在压缩文件中的路径或文件名
* @param data 要压缩的数据
* @return 压缩文件
* @throws UtilException IO异常
* @throws HutoolException IO异常
* @since 3.0.6
*/
public static File zip(final File zipFile, final String path, final String data) throws UtilException {
public static File zip(final File zipFile, final String path, final String data) throws HutoolException {
return zip(zipFile, path, data, DEFAULT_CHARSET);
}
@ -308,10 +308,10 @@ public class ZipUtil {
* @param data 要压缩的数据
* @param charset 编码
* @return 压缩文件
* @throws UtilException IO异常
* @throws HutoolException IO异常
* @since 3.2.2
*/
public static File zip(final File zipFile, final String path, final String data, final Charset charset) throws UtilException {
public static File zip(final File zipFile, final String path, final String data, final Charset charset) throws HutoolException {
return zip(zipFile, path, IoUtil.toStream(data, charset), charset);
}
@ -323,10 +323,10 @@ public class ZipUtil {
* @param path 流数据在压缩文件中的路径或文件名
* @param in 要压缩的源
* @return 压缩文件
* @throws UtilException IO异常
* @throws HutoolException IO异常
* @since 3.0.6
*/
public static File zip(final File zipFile, final String path, final InputStream in) throws UtilException {
public static File zip(final File zipFile, final String path, final InputStream in) throws HutoolException {
return zip(zipFile, path, in, DEFAULT_CHARSET);
}
@ -338,10 +338,10 @@ public class ZipUtil {
* @param in 要压缩的源默认关闭
* @param charset 编码
* @return 压缩文件
* @throws UtilException IO异常
* @throws HutoolException IO异常
* @since 3.2.2
*/
public static File zip(final File zipFile, final String path, final InputStream in, final Charset charset) throws UtilException {
public static File zip(final File zipFile, final String path, final InputStream in, final Charset charset) throws HutoolException {
return zip(zipFile, new String[]{path}, new InputStream[]{in}, charset);
}
@ -353,10 +353,10 @@ public class ZipUtil {
* @param paths 流数据在压缩文件中的路径或文件名
* @param ins 要压缩的源添加完成后自动关闭流
* @return 压缩文件
* @throws UtilException IO异常
* @throws HutoolException IO异常
* @since 3.0.9
*/
public static File zip(final File zipFile, final String[] paths, final InputStream[] ins) throws UtilException {
public static File zip(final File zipFile, final String[] paths, final InputStream[] ins) throws HutoolException {
return zip(zipFile, paths, ins, DEFAULT_CHARSET);
}
@ -369,10 +369,10 @@ public class ZipUtil {
* @param ins 要压缩的源添加完成后自动关闭流
* @param charset 编码
* @return 压缩文件
* @throws UtilException IO异常
* @throws HutoolException IO异常
* @since 3.0.9
*/
public static File zip(final File zipFile, final String[] paths, final InputStream[] ins, final Charset charset) throws UtilException {
public static File zip(final File zipFile, final String[] paths, final InputStream[] ins, final Charset charset) throws HutoolException {
try (final ZipWriter zipWriter = ZipWriter.of(zipFile, charset)) {
zipWriter.add(paths, ins);
}
@ -415,10 +415,10 @@ public class ZipUtil {
* @param charset 编码
* @param resources 需要压缩的资源资源的路径为{@link Resource#getName()}
* @return 压缩文件
* @throws UtilException IO异常
* @throws HutoolException IO异常
* @since 5.5.2
*/
public static File zip(final File zipFile, final Charset charset, final Resource... resources) throws UtilException {
public static File zip(final File zipFile, final Charset charset, final Resource... resources) throws HutoolException {
//noinspection resource
ZipWriter.of(zipFile, charset).add(resources).close();
return zipFile;
@ -431,9 +431,9 @@ public class ZipUtil {
*
* @param zipFilePath 压缩文件路径
* @return 解压的目录
* @throws UtilException IO异常
* @throws HutoolException IO异常
*/
public static File unzip(final String zipFilePath) throws UtilException {
public static File unzip(final String zipFilePath) throws HutoolException {
return unzip(zipFilePath, DEFAULT_CHARSET);
}
@ -443,10 +443,10 @@ public class ZipUtil {
* @param zipFilePath 压缩文件路径
* @param charset 编码
* @return 解压的目录
* @throws UtilException IO异常
* @throws HutoolException IO异常
* @since 3.2.2
*/
public static File unzip(final String zipFilePath, final Charset charset) throws UtilException {
public static File unzip(final String zipFilePath, final Charset charset) throws HutoolException {
return unzip(FileUtil.file(zipFilePath), charset);
}
@ -455,10 +455,10 @@ public class ZipUtil {
*
* @param zipFile 压缩文件
* @return 解压的目录
* @throws UtilException IO异常
* @throws HutoolException IO异常
* @since 3.2.2
*/
public static File unzip(final File zipFile) throws UtilException {
public static File unzip(final File zipFile) throws HutoolException {
return unzip(zipFile, DEFAULT_CHARSET);
}
@ -468,10 +468,10 @@ public class ZipUtil {
* @param zipFile 压缩文件
* @param charset 编码
* @return 解压的目录
* @throws UtilException IO异常
* @throws HutoolException IO异常
* @since 3.2.2
*/
public static File unzip(final File zipFile, final Charset charset) throws UtilException {
public static File unzip(final File zipFile, final Charset charset) throws HutoolException {
final File destDir = FileUtil.file(zipFile.getParentFile(), FileNameUtil.mainName(zipFile));
return unzip(zipFile, destDir, charset);
}
@ -482,9 +482,9 @@ public class ZipUtil {
* @param zipFilePath 压缩文件的路径
* @param outFileDir 解压到的目录
* @return 解压的目录
* @throws UtilException IO异常
* @throws HutoolException IO异常
*/
public static File unzip(final String zipFilePath, final String outFileDir) throws UtilException {
public static File unzip(final String zipFilePath, final String outFileDir) throws HutoolException {
return unzip(zipFilePath, outFileDir, DEFAULT_CHARSET);
}
@ -495,9 +495,9 @@ public class ZipUtil {
* @param outFileDir 解压到的目录
* @param charset 编码
* @return 解压的目录
* @throws UtilException IO异常
* @throws HutoolException IO异常
*/
public static File unzip(final String zipFilePath, final String outFileDir, final Charset charset) throws UtilException {
public static File unzip(final String zipFilePath, final String outFileDir, final Charset charset) throws HutoolException {
return unzip(FileUtil.file(zipFilePath), FileUtil.mkdir(outFileDir), charset);
}
@ -507,9 +507,9 @@ public class ZipUtil {
* @param zipFile zip文件
* @param outFile 解压到的目录
* @return 解压的目录
* @throws UtilException IO异常
* @throws HutoolException IO异常
*/
public static File unzip(final File zipFile, final File outFile) throws UtilException {
public static File unzip(final File zipFile, final File outFile) throws HutoolException {
return unzip(zipFile, outFile, DEFAULT_CHARSET);
}
@ -625,10 +625,10 @@ public class ZipUtil {
* @param outFile 解压到的目录
* @param charset 编码
* @return 解压的目录
* @throws UtilException IO异常
* @throws HutoolException IO异常
* @since 4.5.8
*/
public static File unzip(final InputStream in, final File outFile, Charset charset) throws UtilException {
public static File unzip(final InputStream in, final File outFile, Charset charset) throws HutoolException {
if (null == charset) {
charset = DEFAULT_CHARSET;
}
@ -642,10 +642,10 @@ public class ZipUtil {
* @param zipStream zip文件流包含编码信息
* @param outFile 解压到的目录
* @return 解压的目录
* @throws UtilException IO异常
* @throws HutoolException IO异常
* @since 4.5.8
*/
public static File unzip(final ZipInputStream zipStream, final File outFile) throws UtilException {
public static File unzip(final ZipInputStream zipStream, final File outFile) throws HutoolException {
try (final ZipReader reader = new ZipReader(zipStream)) {
reader.readTo(outFile);
}
@ -725,9 +725,9 @@ public class ZipUtil {
* @param content 被压缩的字符串
* @param charset 编码
* @return 压缩后的字节流
* @throws UtilException IO异常
* @throws HutoolException IO异常
*/
public static byte[] gzip(final String content, final Charset charset) throws UtilException {
public static byte[] gzip(final String content, final Charset charset) throws HutoolException {
return gzip(ByteUtil.toBytes(content, charset));
}
@ -736,9 +736,9 @@ public class ZipUtil {
*
* @param buf 被压缩的字节流
* @return 压缩后的字节流
* @throws UtilException IO异常
* @throws HutoolException IO异常
*/
public static byte[] gzip(final byte[] buf) throws UtilException {
public static byte[] gzip(final byte[] buf) throws HutoolException {
return gzip(new ByteArrayInputStream(buf), buf.length);
}
@ -747,9 +747,9 @@ public class ZipUtil {
*
* @param file 被压缩的文件
* @return 压缩后的字节流
* @throws UtilException IO异常
* @throws HutoolException IO异常
*/
public static byte[] gzip(final File file) throws UtilException {
public static byte[] gzip(final File file) throws HutoolException {
BufferedInputStream in = null;
try {
in = FileUtil.getInputStream(file);
@ -764,10 +764,10 @@ public class ZipUtil {
*
* @param in 被压缩的流
* @return 压缩后的字节流
* @throws UtilException IO异常
* @throws HutoolException IO异常
* @since 4.1.18
*/
public static byte[] gzip(final InputStream in) throws UtilException {
public static byte[] gzip(final InputStream in) throws HutoolException {
return gzip(in, DEFAULT_BYTE_ARRAY_LENGTH);
}
@ -777,10 +777,10 @@ public class ZipUtil {
* @param in 被压缩的流
* @param length 预估长度
* @return 压缩后的字节流
* @throws UtilException IO异常
* @throws HutoolException IO异常
* @since 4.1.18
*/
public static byte[] gzip(final InputStream in, final int length) throws UtilException {
public static byte[] gzip(final InputStream in, final int length) throws HutoolException {
final ByteArrayOutputStream bos = new ByteArrayOutputStream(length);
Gzip.of(in, bos).gzip().close();
return bos.toByteArray();
@ -792,9 +792,9 @@ public class ZipUtil {
* @param buf 压缩过的字节流
* @param charset 编码
* @return 解压后的字符串
* @throws UtilException IO异常
* @throws HutoolException IO异常
*/
public static String unGzip(final byte[] buf, final Charset charset) throws UtilException {
public static String unGzip(final byte[] buf, final Charset charset) throws HutoolException {
return StrUtil.str(unGzip(buf), charset);
}
@ -803,9 +803,9 @@ public class ZipUtil {
*
* @param buf buf
* @return bytes
* @throws UtilException IO异常
* @throws HutoolException IO异常
*/
public static byte[] unGzip(final byte[] buf) throws UtilException {
public static byte[] unGzip(final byte[] buf) throws HutoolException {
return unGzip(new ByteArrayInputStream(buf), buf.length);
}
@ -814,9 +814,9 @@ public class ZipUtil {
*
* @param in Gzip数据
* @return 解压后的数据
* @throws UtilException IO异常
* @throws HutoolException IO异常
*/
public static byte[] unGzip(final InputStream in) throws UtilException {
public static byte[] unGzip(final InputStream in) throws HutoolException {
return unGzip(in, DEFAULT_BYTE_ARRAY_LENGTH);
}
@ -826,10 +826,10 @@ public class ZipUtil {
* @param in Gzip数据
* @param length 估算长度如果无法确定请传入{@link #DEFAULT_BYTE_ARRAY_LENGTH}
* @return 解压后的数据
* @throws UtilException IO异常
* @throws HutoolException IO异常
* @since 4.1.18
*/
public static byte[] unGzip(final InputStream in, final int length) throws UtilException {
public static byte[] unGzip(final InputStream in, final int length) throws HutoolException {
final FastByteArrayOutputStream bos = new FastByteArrayOutputStream(length);
Gzip.of(in, bos).unGzip().close();
return bos.toByteArray();
@ -993,9 +993,9 @@ public class ZipUtil {
* @param zipFile 压缩后的产生的文件路径
* @param srcFiles 被压缩的文件或目录
*/
private static void validateFiles(final File zipFile, final File... srcFiles) throws UtilException {
private static void validateFiles(final File zipFile, final File... srcFiles) throws HutoolException {
if (zipFile.isDirectory()) {
throw new UtilException("Zip file [{}] must not be a directory !", zipFile.getAbsoluteFile());
throw new HutoolException("Zip file [{}] must not be a directory !", zipFile.getAbsoluteFile());
}
for (final File srcFile : srcFiles) {
@ -1003,7 +1003,7 @@ public class ZipUtil {
continue;
}
if (!srcFile.exists()) {
throw new UtilException(StrUtil.format("File [{}] not exist!", srcFile.getAbsolutePath()));
throw new HutoolException(StrUtil.format("File [{}] not exist!", srcFile.getAbsolutePath()));
}
// issue#1961@Github
@ -1017,7 +1017,7 @@ public class ZipUtil {
// 压缩文件不能位于被压缩的目录内
if (srcFile.isDirectory() && FileUtil.isSub(srcFile, parentFile)) {
throw new UtilException("Zip file path [{}] must not be the child directory of [{}] !", zipFile.getPath(), srcFile.getPath());
throw new HutoolException("Zip file path [{}] must not be the child directory of [{}] !", zipFile.getPath(), srcFile.getPath());
}
}
}

View File

@ -24,12 +24,56 @@ import java.util.Set;
* @author xiaoleilu
*/
public enum BasicType {
BYTE, SHORT, INT, INTEGER, LONG, DOUBLE, FLOAT, BOOLEAN, CHAR, CHARACTER, STRING;
/**
* byte
*/
BYTE,
/**
* short
*/
SHORT,
/**
* int
*/
INT,
/**
* {@link Integer}
*/
INTEGER,
/**
* long
*/
LONG,
/**
* double
*/
DOUBLE,
/**
* float
*/
FLOAT,
/**
* boolean
*/
BOOLEAN,
/**
* char
*/
CHAR,
/**
* {@link Character}
*/
CHARACTER,
/**
* {@link String}
*/
STRING;
/**
* 包装类型为Key原始类型为Value例如 Integer.class = int.class.
*/
private static final BiMap<Class<?>, Class<?>> WRAPPER_PRIMITIVE_MAP = new BiMap<>(new HashMap<>(8, 1));
static {
WRAPPER_PRIMITIVE_MAP.put(Boolean.class, boolean.class);
WRAPPER_PRIMITIVE_MAP.put(Byte.class, byte.class);
@ -54,11 +98,11 @@ public enum BasicType {
/**
* 原始类转为包装类非原始类返回原类
*
* @param clazz 原始类
* @param clazz 原始类
* @param errorReturnNull 如果没有对应类的原始类型是否返回{@code null}{@code true}返回{@code null}否则返回原class
* @return 包装类
*/
public static Class<?> wrap(final Class<?> clazz, boolean errorReturnNull) {
public static Class<?> wrap(final Class<?> clazz, final boolean errorReturnNull) {
if (null == clazz || !clazz.isPrimitive()) {
return clazz;
}

View File

@ -13,19 +13,19 @@
package org.dromara.hutool.core.exceptions;
/**
* InvocationTargetException的运行时异常
* 克隆异常
*
* @author looly
* @author xiaoleilu
*/
public class InvocationTargetRuntimeException extends UtilException {
private static final long serialVersionUID = 1L;
public class CloneException extends HutoolException {
private static final long serialVersionUID = 6774837422188798989L;
/**
* 构造
*
* @param e 异常
*/
public InvocationTargetRuntimeException(final Throwable e) {
public CloneException(final Throwable e) {
super(e);
}
@ -34,7 +34,7 @@ public class InvocationTargetRuntimeException extends UtilException {
*
* @param message 消息
*/
public InvocationTargetRuntimeException(final String message) {
public CloneException(final String message) {
super(message);
}
@ -44,7 +44,7 @@ public class InvocationTargetRuntimeException extends UtilException {
* @param messageTemplate 消息模板
* @param params 参数
*/
public InvocationTargetRuntimeException(final String messageTemplate, final Object... params) {
public CloneException(final String messageTemplate, final Object... params) {
super(messageTemplate, params);
}
@ -54,7 +54,7 @@ public class InvocationTargetRuntimeException extends UtilException {
* @param message 消息
* @param cause 被包装的子异常
*/
public InvocationTargetRuntimeException(final String message, final Throwable cause) {
public CloneException(final String message, final Throwable cause) {
super(message, cause);
}
@ -66,7 +66,7 @@ public class InvocationTargetRuntimeException extends UtilException {
* @param enableSuppression 是否启用抑制
* @param writableStackTrace 堆栈跟踪是否应该是可写的
*/
public InvocationTargetRuntimeException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) {
public CloneException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
@ -77,7 +77,7 @@ public class InvocationTargetRuntimeException extends UtilException {
* @param messageTemplate 消息模板
* @param params 参数
*/
public InvocationTargetRuntimeException(final Throwable cause, final String messageTemplate, final Object... params) {
public CloneException(final Throwable cause, final String messageTemplate, final Object... params) {
super(cause, messageTemplate, params);
}
}

View File

@ -1,43 +0,0 @@
/*
* Copyright (c) 2023 looly(loolly@aliyun.com)
* Hutool is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
package org.dromara.hutool.core.exceptions;
import org.dromara.hutool.core.text.StrUtil;
/**
* 克隆异常
* @author xiaoleilu
*/
public class CloneRuntimeException extends RuntimeException{
private static final long serialVersionUID = 6774837422188798989L;
public CloneRuntimeException(final Throwable e) {
super(ExceptionUtil.getMessage(e), e);
}
public CloneRuntimeException(final String message) {
super(message);
}
public CloneRuntimeException(final String messageTemplate, final Object... params) {
super(StrUtil.format(messageTemplate, params));
}
public CloneRuntimeException(final String message, final Throwable throwable) {
super(message, throwable);
}
public CloneRuntimeException(final Throwable throwable, final String messageTemplate, final Object... params) {
super(StrUtil.format(messageTemplate, params), throwable);
}
}

View File

@ -12,38 +12,73 @@
package org.dromara.hutool.core.exceptions;
import org.dromara.hutool.core.text.StrUtil;
/**
* 依赖异常
*
* @author xiaoleilu
* @since 4.0.10
*/
public class DependencyException extends RuntimeException {
private static final long serialVersionUID = 8247610319171014183L;
public class DependencyException extends HutoolException {
private static final long serialVersionUID = 1L;
/**
* 构造
*
* @param e 异常
*/
public DependencyException(final Throwable e) {
super(ExceptionUtil.getMessage(e), e);
super(e);
}
/**
* 构造
*
* @param message 消息
*/
public DependencyException(final String message) {
super(message);
}
/**
* 构造
*
* @param messageTemplate 消息模板
* @param params 参数
*/
public DependencyException(final String messageTemplate, final Object... params) {
super(StrUtil.format(messageTemplate, params));
super(messageTemplate, params);
}
public DependencyException(final String message, final Throwable throwable) {
super(message, throwable);
/**
* 构造
*
* @param message 消息
* @param cause 被包装的子异常
*/
public DependencyException(final String message, final Throwable cause) {
super(message, cause);
}
public DependencyException(final String message, final Throwable throwable, final boolean enableSuppression, final boolean writableStackTrace) {
super(message, throwable, enableSuppression, writableStackTrace);
/**
* 构造
*
* @param message 消息
* @param cause 被包装的子异常
* @param enableSuppression 是否启用抑制
* @param writableStackTrace 堆栈跟踪是否应该是可写的
*/
public DependencyException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public DependencyException(final Throwable throwable, final String messageTemplate, final Object... params) {
super(StrUtil.format(messageTemplate, params), throwable);
/**
* 构造
*
* @param cause 被包装的子异常
* @param messageTemplate 消息模板
* @param params 参数
*/
public DependencyException(final Throwable cause, final String messageTemplate, final Object... params) {
super(cause, messageTemplate, params);
}
}

View File

@ -0,0 +1,93 @@
/*
* Copyright (c) 2023 looly(loolly@aliyun.com)
* Hutool is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
package org.dromara.hutool.core.exceptions;
import org.dromara.hutool.core.text.StrUtil;
/**
* Hutool工具类异常
*
* @author looly
* @since 6.0.0
*/
public class HutoolException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* 构造
*/
public HutoolException() {
super();
}
/**
* 构造
*
* @param e 异常
*/
public HutoolException(final Throwable e) {
super(e);
}
/**
* 构造
*
* @param message 消息
*/
public HutoolException(final String message) {
super(message);
}
/**
* 构造
*
* @param messageTemplate 消息模板
* @param params 参数
*/
public HutoolException(final String messageTemplate, final Object... params) {
super(StrUtil.format(messageTemplate, params));
}
/**
* 构造
*
* @param message 消息
* @param cause 被包装的子异常
*/
public HutoolException(final String message, final Throwable cause) {
super(message, cause);
}
/**
* 构造
*
* @param message 消息
* @param cause 被包装的子异常
* @param enableSuppression 是否启用抑制
* @param writableStackTrace 堆栈跟踪是否应该是可写的
*/
public HutoolException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
/**
* 构造
*
* @param cause 被包装的子异常
* @param messageTemplate 消息模板
* @param params 参数
*/
public HutoolException(final Throwable cause, final String messageTemplate, final Object... params) {
super(StrUtil.format(messageTemplate, params), cause);
}
}

View File

@ -12,37 +12,72 @@
package org.dromara.hutool.core.exceptions;
import org.dromara.hutool.core.text.StrUtil;
/**
* 未初始化异常
*
* @author xiaoleilu
*/
public class NotInitedException extends RuntimeException {
public class NotInitedException extends HutoolException {
private static final long serialVersionUID = 8247610319171014183L;
/**
* 构造
*
* @param e 异常
*/
public NotInitedException(final Throwable e) {
super(e);
}
/**
* 构造
*
* @param message 消息
*/
public NotInitedException(final String message) {
super(message);
}
/**
* 构造
*
* @param messageTemplate 消息模板
* @param params 参数
*/
public NotInitedException(final String messageTemplate, final Object... params) {
super(StrUtil.format(messageTemplate, params));
super(messageTemplate, params);
}
public NotInitedException(final String message, final Throwable throwable) {
super(message, throwable);
/**
* 构造
*
* @param message 消息
* @param cause 被包装的子异常
*/
public NotInitedException(final String message, final Throwable cause) {
super(message, cause);
}
public NotInitedException(final String message, final Throwable throwable, final boolean enableSuppression, final boolean writableStackTrace) {
super(message, throwable, enableSuppression, writableStackTrace);
/**
* 构造
*
* @param message 消息
* @param cause 被包装的子异常
* @param enableSuppression 是否启用抑制
* @param writableStackTrace 堆栈跟踪是否应该是可写的
*/
public NotInitedException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public NotInitedException(final Throwable throwable, final String messageTemplate, final Object... params) {
super(StrUtil.format(messageTemplate, params), throwable);
/**
* 构造
*
* @param cause 被包装的子异常
* @param messageTemplate 消息模板
* @param params 参数
*/
public NotInitedException(final Throwable cause, final String messageTemplate, final Object... params) {
super(cause, messageTemplate, params);
}
}

View File

@ -12,52 +12,112 @@
package org.dromara.hutool.core.exceptions;
import org.dromara.hutool.core.text.StrUtil;
/**
* 带有状态码的异常
*
* @author xiaoleilu
* @author looly
*/
public class StatefulException extends RuntimeException {
private static final long serialVersionUID = 6057602589533840889L;
public class StatefulException extends HutoolException {
private static final long serialVersionUID = 1L;
// 异常状态码
private int status;
/**
* 构造
*/
public StatefulException() {
super();
}
public StatefulException(final String msg) {
super(msg);
/**
* 构造
*
* @param e 异常
*/
public StatefulException(final Throwable e) {
super(e);
}
/**
* 构造
*
* @param message 消息
*/
public StatefulException(final String message) {
super(message);
}
/**
* 构造
*
* @param messageTemplate 消息模板
* @param params 参数
*/
public StatefulException(final String messageTemplate, final Object... params) {
super(StrUtil.format(messageTemplate, params));
super(messageTemplate, params);
}
public StatefulException(final Throwable throwable) {
super(throwable);
/**
* 构造
*
* @param message 消息
* @param cause 被包装的子异常
*/
public StatefulException(final String message, final Throwable cause) {
super(message, cause);
}
public StatefulException(final String msg, final Throwable throwable) {
super(msg, throwable);
/**
* 构造
*
* @param message 消息
* @param cause 被包装的子异常
* @param enableSuppression 是否启用抑制
* @param writableStackTrace 堆栈跟踪是否应该是可写的
*/
public StatefulException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public StatefulException(final String message, final Throwable throwable, final boolean enableSuppression, final boolean writableStackTrace) {
super(message, throwable, enableSuppression, writableStackTrace);
/**
* 构造
*
* @param cause 被包装的子异常
* @param messageTemplate 消息模板
* @param params 参数
*/
public StatefulException(final Throwable cause, final String messageTemplate, final Object... params) {
super(cause, messageTemplate, params);
}
/**
* 构造
*
* @param status 状态码
* @param msg 消息
*/
public StatefulException(final int status, final String msg) {
super(msg);
this.status = status;
}
/**
* 构造
*
* @param status 状态码
* @param throwable 异常
*/
public StatefulException(final int status, final Throwable throwable) {
super(throwable);
this.status = status;
}
/**
* @param status 状态码
* @param msg 消息
* @param throwable 异常
*/
public StatefulException(final int status, final String msg, final Throwable throwable) {
super(msg, throwable);
this.status = status;

View File

@ -1,48 +0,0 @@
/*
* Copyright (c) 2023 looly(loolly@aliyun.com)
* Hutool is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
package org.dromara.hutool.core.exceptions;
import org.dromara.hutool.core.text.StrUtil;
/**
* 工具类异常
*
* @author xiaoleilu
*/
public class UtilException extends RuntimeException {
private static final long serialVersionUID = 8247610319171014183L;
public UtilException(final Throwable cause) {
super(ExceptionUtil.getMessage(cause), cause);
}
public UtilException(final String message) {
super(message);
}
public UtilException(final String messageTemplate, final Object... params) {
super(StrUtil.format(messageTemplate, params));
}
public UtilException(final String message, final Throwable cause) {
super(message, cause);
}
public UtilException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public UtilException(final Throwable cause, final String messageTemplate, final Object... params) {
super(StrUtil.format(messageTemplate, params), cause);
}
}

View File

@ -12,8 +12,6 @@
package org.dromara.hutool.core.exceptions;
import org.dromara.hutool.core.text.StrUtil;
/**
* 验证异常
*
@ -22,37 +20,99 @@ import org.dromara.hutool.core.text.StrUtil;
public class ValidateException extends StatefulException {
private static final long serialVersionUID = 6057602589533840889L;
/**
* 构造
*/
public ValidateException() {
super();
}
public ValidateException(final String msg) {
super(msg);
/**
* 构造
*
* @param e 异常
*/
public ValidateException(final Throwable e) {
super(e);
}
/**
* 构造
*
* @param message 消息
*/
public ValidateException(final String message) {
super(message);
}
/**
* 构造
*
* @param messageTemplate 消息模板
* @param params 参数
*/
public ValidateException(final String messageTemplate, final Object... params) {
super(StrUtil.format(messageTemplate, params));
super(messageTemplate, params);
}
public ValidateException(final Throwable throwable) {
super(throwable);
/**
* 构造
*
* @param message 消息
* @param cause 被包装的子异常
*/
public ValidateException(final String message, final Throwable cause) {
super(message, cause);
}
public ValidateException(final String msg, final Throwable throwable) {
super(msg, throwable);
/**
* 构造
*
* @param message 消息
* @param cause 被包装的子异常
* @param enableSuppression 是否启用抑制
* @param writableStackTrace 堆栈跟踪是否应该是可写的
*/
public ValidateException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
/**
* 构造
*
* @param cause 被包装的子异常
* @param messageTemplate 消息模板
* @param params 参数
*/
public ValidateException(final Throwable cause, final String messageTemplate, final Object... params) {
super(cause, messageTemplate, params);
}
/**
* 构造
*
* @param status 状态码
* @param msg 消息
*/
public ValidateException(final int status, final String msg) {
super(status, msg);
}
/**
* 构造
*
* @param status 状态码
* @param throwable 异常
*/
public ValidateException(final int status, final Throwable throwable) {
super(status, throwable);
}
public ValidateException(final String message, final Throwable throwable, final boolean enableSuppression, final boolean writableStackTrace) {
super(message, throwable, enableSuppression, writableStackTrace);
}
/**
* @param status 状态码
* @param msg 消息
* @param throwable 异常
*/
public ValidateException(final int status, final String msg, final Throwable throwable) {
super(status, msg, throwable);
}

View File

@ -12,24 +12,17 @@
package org.dromara.hutool.core.func;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.lang.mutable.MutableEntry;
import org.dromara.hutool.core.map.WeakConcurrentMap;
import org.dromara.hutool.core.reflect.MethodUtil;
import org.dromara.hutool.core.reflect.ModifierUtil;
import org.dromara.hutool.core.reflect.ReflectUtil;
import org.dromara.hutool.core.reflect.*;
import org.dromara.hutool.core.reflect.lookup.LookupUtil;
import java.io.Serializable;
import java.lang.invoke.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 以类似反射的方式动态创建Lambda在性能上有一定优势同时避免每次调用Lambda时创建匿名内部类
@ -82,55 +75,71 @@ public class LambdaFactory {
public static <F> F build(final Class<F> functionInterfaceType, final Executable executable) {
Assert.notNull(functionInterfaceType);
Assert.notNull(executable);
final MutableEntry<Class<?>, Executable> cacheKey = new MutableEntry<>(functionInterfaceType, executable);
return (F) CACHE.computeIfAbsent(cacheKey, key -> {
final List<Method> abstractMethods = Arrays.stream(functionInterfaceType.getMethods())
.filter(ModifierUtil::isAbstract)
.collect(Collectors.toList());
Assert.equals(abstractMethods.size(), 1, "不支持非函数式接口");
ReflectUtil.setAccessible(executable);
return (F) CACHE.computeIfAbsent(cacheKey,
key -> doBuildWithoutCache(functionInterfaceType, executable));
}
final MethodHandle methodHandle = LookupUtil.unreflect(executable);
final MethodType instantiatedMethodType;
if (executable instanceof Method) {
final Method method = (Method) executable;
instantiatedMethodType = MethodType.methodType(method.getReturnType(), method.getDeclaringClass(), method.getParameterTypes());
} else {
final Constructor<?> constructor = (Constructor<?>) executable;
instantiatedMethodType = MethodType.methodType(constructor.getDeclaringClass(), constructor.getParameterTypes());
}
final boolean isSerializable = Serializable.class.isAssignableFrom(functionInterfaceType);
/**
* 根据提供的方法或构造对象构建对应的Lambda函数<br>
* 调用函数相当于执行对应的方法或构造
*
* @param funcType 接受Lambda的函数式接口类型
* @param executable 方法对象支持构造器
* @param <F> Function类型
* @return 接受Lambda的函数式接口对象
*/
@SuppressWarnings("unchecked")
private static <F> F doBuildWithoutCache(final Class<F> funcType, final Executable executable) {
ReflectUtil.setAccessible(executable);
final Method invokeMethod = abstractMethods.get(0);
final MethodHandles.Lookup caller = LookupUtil.lookup(executable.getDeclaringClass());
final String invokeName = invokeMethod.getName();
final MethodType invokedType = MethodType.methodType(functionInterfaceType);
final MethodType samMethodType = MethodType.methodType(invokeMethod.getReturnType(), invokeMethod.getParameterTypes());
try {
final CallSite callSite = isSerializable ?
LambdaMetafactory.altMetafactory(
caller,
invokeName,
invokedType,
samMethodType,
methodHandle,
instantiatedMethodType,
LambdaMetafactory.FLAG_SERIALIZABLE
) :
LambdaMetafactory.metafactory(
caller,
invokeName,
invokedType,
samMethodType,
methodHandle,
instantiatedMethodType
);
//noinspection unchecked
return (F) callSite.getTarget().invoke();
} catch (final Throwable e) {
throw new UtilException(e);
}
});
try {
return (F) metaFactory(funcType, executable).getTarget().invoke();
} catch (final Throwable e) {
throw new HutoolException(e);
}
}
/**
* 使用给定的函数接口代理指定方法或构造
*
* @param functionInterfaceType 函数接口
* @param executable 方法或构造
* @return 函数锚点
* @throws LambdaConversionException 权限等异常
*/
private static CallSite metaFactory(final Class<?> functionInterfaceType, final Executable executable) throws LambdaConversionException {
// 被代理的方法
final Method[] abstractMethods = MethodUtil.getPublicMethods(functionInterfaceType, ModifierUtil::isAbstract);
Assert.equals(abstractMethods.length, 1, "Class is not a functional interface.");
final Method invokeMethod = abstractMethods[0];
final MethodHandle methodHandle = LookupUtil.unreflect(executable);
final MethodHandles.Lookup caller = LookupUtil.lookup();
final String invokeName = invokeMethod.getName();
final MethodType invokedType = MethodType.methodType(functionInterfaceType);
final MethodType samMethodType = MethodType.methodType(invokeMethod.getReturnType(), invokeMethod.getParameterTypes());
if(ClassUtil.isSerializable(functionInterfaceType)){
return LambdaMetafactory.altMetafactory(
caller,
invokeName,
invokedType,
samMethodType,
methodHandle,
MethodTypeUtil.methodType(executable),
LambdaMetafactory.FLAG_SERIALIZABLE
);
}
return LambdaMetafactory.metafactory(
caller,
invokeName,
invokedType,
samMethodType,
methodHandle,
MethodTypeUtil.methodType(executable)
);
}
}

View File

@ -14,7 +14,7 @@ package org.dromara.hutool.core.func;
import org.dromara.hutool.core.bean.BeanUtil;
import org.dromara.hutool.core.classloader.ClassLoaderUtil;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.lang.Opt;
import org.dromara.hutool.core.map.WeakConcurrentMap;
import org.dromara.hutool.core.reflect.MethodUtil;
@ -290,7 +290,7 @@ public class LambdaUtil {
if (serLambda instanceof SerializedLambda) {
return (SerializedLambda) serLambda;
}
throw new UtilException("writeReplace result value is not java.lang.invoke.SerializedLambda");
throw new HutoolException("writeReplace result value is not java.lang.invoke.SerializedLambda");
}
//endregion
}

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.func;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import java.io.Serializable;
import java.util.Objects;
@ -62,7 +62,7 @@ public interface SerBiConsumer<T, U> extends BiConsumer<T, U>, Serializable {
try {
accepting(t, u);
} catch (final Exception e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.func;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import java.io.Serializable;
import java.util.Objects;
@ -52,7 +52,7 @@ public interface SerBiFunction<T, U, R> extends BiFunction<T, U, R>, Serializabl
try {
return this.applying(t, u);
} catch (final Exception e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.func;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import java.io.Serializable;
import java.util.Objects;
@ -54,7 +54,7 @@ public interface SerBiPredicate<T, U> extends BiPredicate<T, U>, Serializable {
try {
return testing(t, u);
} catch (final Exception e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.func;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import java.io.Serializable;
import java.util.Comparator;
@ -51,7 +51,7 @@ public interface SerBinaryOperator<T> extends BinaryOperator<T>, Serializable {
try {
return this.applying(t, u);
} catch (final Exception e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.func;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import java.io.Serializable;
import java.util.Objects;
@ -47,7 +47,7 @@ public interface SerConsumer<T> extends Consumer<T>, Serializable {
try {
accepting(t);
} catch (final Exception e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.func;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import java.io.Serializable;
import java.util.Objects;
@ -50,7 +50,7 @@ public interface SerConsumer3<P1, P2, P3> extends Serializable {
try {
accepting(p1, p2, p3);
} catch (final Exception e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.func;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import java.io.Serializable;
import java.util.function.Function;
@ -48,7 +48,7 @@ public interface SerFunction<T, R> extends Function<T, R>, Serializable {
try {
return applying(t);
} catch (final Exception e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.func;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import java.io.Serializable;
import java.util.Objects;
@ -51,7 +51,7 @@ public interface SerPredicate<T> extends Predicate<T>, Serializable {
try {
return testing(t);
} catch (final Exception e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}

View File

@ -13,7 +13,7 @@
package org.dromara.hutool.core.func;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import java.io.Serializable;
import java.util.stream.Stream;
@ -57,7 +57,7 @@ public interface SerRunnable extends Runnable, Serializable {
try {
running();
} catch (final Exception e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.func;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import java.io.Serializable;
import java.util.function.Supplier;
@ -46,7 +46,7 @@ public interface SerSupplier<R> extends Supplier<R>, Serializable {
try {
return getting();
} catch (final Exception e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.func;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import java.io.Serializable;
import java.util.function.Function;
@ -48,7 +48,7 @@ public interface SerUnaryOperator<T> extends UnaryOperator<T>, Serializable {
try {
return applying(t);
} catch (final Exception e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}

View File

@ -14,7 +14,7 @@ package org.dromara.hutool.core.io;
import org.dromara.hutool.core.codec.HexUtil;
import org.dromara.hutool.core.collection.iter.LineIter;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.io.copy.FileChannelCopier;
import org.dromara.hutool.core.io.copy.ReaderWriterCopier;
import org.dromara.hutool.core.io.copy.StreamCopier;
@ -419,9 +419,9 @@ public class IoUtil extends NioUtil {
* @param acceptClasses 读取对象类型
* @return 输出流
* @throws IORuntimeException IO异常
* @throws UtilException ClassNotFoundException包装
* @throws HutoolException ClassNotFoundException包装
*/
public static <T> T readObj(final InputStream in, final Class<?>... acceptClasses) throws IORuntimeException, UtilException {
public static <T> T readObj(final InputStream in, final Class<?>... acceptClasses) throws IORuntimeException, HutoolException {
return StreamReader.of(in, false).readObj(acceptClasses);
}

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.io;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.io.stream.FastByteArrayOutputStream;
import java.io.ByteArrayInputStream;
@ -34,7 +34,7 @@ public class SerializeUtil {
* @param <T> 对象类型
* @param obj 被克隆对象
* @return 克隆后的对象
* @throws UtilException IO异常和ClassNotFoundException封装
* @throws HutoolException IO异常和ClassNotFoundException封装
*/
public static <T> T clone(final T obj) {
if (!(obj instanceof Serializable)) {

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.io.file;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.func.SerConsumer;
import org.dromara.hutool.core.func.SerFunction;
import org.dromara.hutool.core.io.IORuntimeException;
@ -170,7 +170,7 @@ public class FileReader extends FileWrapper {
} else if(e instanceof RuntimeException){
throw (RuntimeException)e;
} else{
throw new UtilException(e);
throw new HutoolException(e);
}
} finally {
IoUtil.closeQuietly(reader);

View File

@ -13,7 +13,7 @@
package org.dromara.hutool.core.io.file;
import org.dromara.hutool.core.date.DateUnit;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.io.IORuntimeException;
import org.dromara.hutool.core.io.IoUtil;
import org.dromara.hutool.core.lang.Console;
@ -141,7 +141,7 @@ public class Tailer implements Serializable {
try {
scheduledFuture.get();
} catch (final ExecutionException e) {
throw new UtilException(e);
throw new HutoolException(e);
} catch (final InterruptedException e) {
// ignore and exist
}
@ -226,10 +226,10 @@ public class Tailer implements Serializable {
*/
private static void checkFile(final File file) {
if (!file.exists()) {
throw new UtilException("File [{}] not exist !", file.getAbsolutePath());
throw new HutoolException("File [{}] not exist !", file.getAbsolutePath());
}
if (!file.isFile()) {
throw new UtilException("Path [{}] is not a file !", file.getAbsolutePath());
throw new HutoolException("Path [{}] is not a file !", file.getAbsolutePath());
}
}
// ---------------------------------------------------------------------------------------- Private method end

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.io.stream;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.io.IORuntimeException;
import org.dromara.hutool.core.io.IoUtil;
@ -138,10 +138,10 @@ public class StreamReader {
* @param acceptClasses 读取对象类型
* @return 输出流
* @throws IORuntimeException IO异常
* @throws UtilException ClassNotFoundException包装
* @throws HutoolException ClassNotFoundException包装
*/
@SuppressWarnings("unchecked")
public <T> T readObj(final Class<?>... acceptClasses) throws IORuntimeException, UtilException {
public <T> T readObj(final Class<?>... acceptClasses) throws IORuntimeException, HutoolException {
final InputStream in = this.in;
if (null == in) {
return null;
@ -166,7 +166,7 @@ public class StreamReader {
} catch (final IOException e) {
throw new IORuntimeException(e);
} catch (final ClassNotFoundException e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}
}

View File

@ -14,7 +14,7 @@ package org.dromara.hutool.core.lang.caller;
import java.io.Serializable;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
/**
* 通过StackTrace方式获取调用者此方式效率最低不推荐使用
@ -35,7 +35,7 @@ public class StackTraceCaller implements Caller, Serializable {
try {
return Class.forName(className);
} catch (final ClassNotFoundException e) {
throw new UtilException(e, "[{}] not found!", className);
throw new HutoolException(e, "[{}] not found!", className);
}
}
@ -49,7 +49,7 @@ public class StackTraceCaller implements Caller, Serializable {
try {
return Class.forName(className);
} catch (final ClassNotFoundException e) {
throw new UtilException(e, "[{}] not found!", className);
throw new HutoolException(e, "[{}] not found!", className);
}
}
@ -63,7 +63,7 @@ public class StackTraceCaller implements Caller, Serializable {
try {
return Class.forName(className);
} catch (final ClassNotFoundException e) {
throw new UtilException(e, "[{}] not found!", className);
throw new HutoolException(e, "[{}] not found!", className);
}
}

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.lang.id;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.lang.Singleton;
import org.dromara.hutool.core.net.Ipv4Util;
@ -190,7 +190,7 @@ public class IdUtil {
byte[] mac = null;
try{
mac = Ipv4Util.getLocalHardwareAddress();
}catch (final UtilException ignore){
}catch (final HutoolException ignore){
// ignore
}
if (null != mac) {
@ -220,7 +220,7 @@ public class IdUtil {
mpid.append(datacenterId);
try {
mpid.append(RuntimeUtil.getPid());
} catch (final UtilException igonre) {
} catch (final HutoolException igonre) {
//ignore
}
/*

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.lang.id;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.text.StrUtil;
import java.lang.management.ManagementFactory;
@ -46,12 +46,12 @@ public enum Pid {
* 获取当前进程ID首先获取进程名称读取@前的ID值如果不存在则读取进程名的hash值
*
* @return 进程ID
* @throws UtilException 进程名称为空
* @throws HutoolException 进程名称为空
*/
private static int getPid() throws UtilException {
private static int getPid() throws HutoolException {
final String processName = ManagementFactory.getRuntimeMXBean().getName();
if (StrUtil.isBlank(processName)) {
throw new UtilException("Process name is blank!");
throw new HutoolException("Process name is blank!");
}
final int atIndex = processName.indexOf('@');
if (atIndex > 0) {

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.lang.tuple;
import org.dromara.hutool.core.exceptions.CloneRuntimeException;
import org.dromara.hutool.core.exceptions.CloneException;
import java.io.Serializable;
import java.util.Objects;
@ -123,7 +123,7 @@ public class Triple<L, M, R> implements Serializable, Cloneable {
try {
return (Triple<L, M, R>) super.clone();
} catch (final CloneNotSupportedException e) {
throw new CloneRuntimeException(e);
throw new CloneException(e);
}
}
}

View File

@ -14,7 +14,7 @@ package org.dromara.hutool.core.lang.tuple;
import org.dromara.hutool.core.collection.ListUtil;
import org.dromara.hutool.core.collection.iter.ArrayIter;
import org.dromara.hutool.core.exceptions.CloneRuntimeException;
import org.dromara.hutool.core.exceptions.CloneException;
import org.dromara.hutool.core.array.ArrayUtil;
import java.io.Serializable;
@ -194,7 +194,7 @@ public class Tuple implements Iterable<Object>, Serializable, Cloneable {
try {
return (Tuple) super.clone();
} catch (final CloneNotSupportedException e) {
throw new CloneRuntimeException(e);
throw new CloneException(e);
}
}
}

View File

@ -17,7 +17,7 @@ import org.dromara.hutool.core.bean.BeanUtil;
import org.dromara.hutool.core.bean.copier.CopyOptions;
import org.dromara.hutool.core.collection.set.SetUtil;
import org.dromara.hutool.core.convert.Convert;
import org.dromara.hutool.core.exceptions.CloneRuntimeException;
import org.dromara.hutool.core.exceptions.CloneException;
import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.func.LambdaInfo;
import org.dromara.hutool.core.func.LambdaUtil;
@ -466,7 +466,7 @@ public class Dict extends CustomKeyMap<String, Object> implements TypeGetter<Str
try {
return (Dict) super.clone();
} catch (final CloneNotSupportedException e) {
throw new CloneRuntimeException(e);
throw new CloneException(e);
}
}

View File

@ -17,7 +17,6 @@ import org.dromara.hutool.core.collection.CollUtil;
import org.dromara.hutool.core.collection.ListUtil;
import org.dromara.hutool.core.collection.iter.ArrayIter;
import org.dromara.hutool.core.collection.iter.IterUtil;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.reflect.ConstructorUtil;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.util.ObjUtil;
@ -248,7 +247,7 @@ public class MapUtil extends MapGetUtil {
} else {
try {
return (Map<K, V>) ConstructorUtil.newInstance(mapType);
} catch (final UtilException e) {
} catch (final Exception e) {
// 不支持的map类型返回默认的HashMap
return new HashMap<>();
}

View File

@ -26,8 +26,8 @@ import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Collection;
import java.util.Objects;
import java.util.Locale;
import java.util.Objects;
/**
* 数字工具类<br>
@ -47,7 +47,6 @@ import java.util.Locale;
* <ul>
* <li><a href="https://github.com/venusdrogon/feilong-core/wiki/one-jdk7-bug-thinking">one-jdk7-bug-thinking</a></li>
* </ul>
* <p>
*
* @author Looly
*/

View File

@ -13,7 +13,7 @@
package org.dromara.hutool.core.net;
import org.dromara.hutool.core.collection.CollUtil;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.lang.Singleton;
import java.math.BigInteger;
@ -199,7 +199,7 @@ public class Ipv6Util {
try {
return InetAddress.getByName(addr.substring(0, index) + '%' + address.getScopeId());
} catch (final UnknownHostException e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}
return address;

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.net;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import java.net.InetAddress;
import java.net.NetworkInterface;
@ -70,7 +70,7 @@ public class MacAddressUtil {
return networkInterface.getHardwareAddress();
}
} catch (final SocketException e) {
throw new UtilException(e);
throw new HutoolException(e);
}
return null;
}

View File

@ -14,7 +14,7 @@ package org.dromara.hutool.core.net;
import org.dromara.hutool.core.collection.CollUtil;
import org.dromara.hutool.core.collection.iter.EnumerationIter;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.io.IORuntimeException;
import org.dromara.hutool.core.io.IoUtil;
import org.dromara.hutool.core.text.StrUtil;
@ -163,7 +163,7 @@ public class NetUtil {
}
}
throw new UtilException("Could not find an available port in the range [{}, {}] after {} attempts", minPort, maxPort, maxPort - minPort);
throw new HutoolException("Could not find an available port in the range [{}, {}] after {} attempts", minPort, maxPort, maxPort - minPort);
}
/**
@ -184,7 +184,7 @@ public class NetUtil {
}
if (availablePorts.size() != numRequested) {
throw new UtilException("Could not find {} available ports in the range [{}, {}]", numRequested, minPort, maxPort);
throw new HutoolException("Could not find {} available ports in the range [{}, {}]", numRequested, minPort, maxPort);
}
return availablePorts;
@ -220,7 +220,7 @@ public class NetUtil {
final URL absoluteUrl = new URL(absoluteBasePath);
return new URL(absoluteUrl, relativePath).toString();
} catch (final Exception e) {
throw new UtilException(e, "To absolute url [{}] base [{}] error!", relativePath, absoluteBasePath);
throw new HutoolException(e, "To absolute url [{}] base [{}] error!", relativePath, absoluteBasePath);
}
}
@ -364,11 +364,11 @@ public class NetUtil {
try {
networkInterfaces = NetworkInterface.getNetworkInterfaces();
} catch (final SocketException e) {
throw new UtilException(e);
throw new HutoolException(e);
}
if (networkInterfaces == null) {
throw new UtilException("Get network interface error!");
throw new HutoolException("Get network interface error!");
}
final LinkedHashSet<InetAddress> ipSet = new LinkedHashSet<>();

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.net.ssl;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.io.IORuntimeException;
import org.dromara.hutool.core.text.StrUtil;
@ -66,12 +66,12 @@ public class SSLUtil {
tmf = TrustManagerFactory.getInstance(algorithm, provider);
}
} catch (final NoSuchAlgorithmException e) {
throw new UtilException(e);
throw new HutoolException(e);
}
try {
tmf.init(keyStore);
} catch (final KeyStoreException e) {
throw new UtilException(e);
throw new HutoolException(e);
}
final TrustManager[] tms = tmf.getTrustManagers();

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.net.url;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.util.CharUtil;
import org.dromara.hutool.core.util.CharsetUtil;
@ -37,7 +37,7 @@ public class URLEncoder {
*
* @param url URL
* @return 编码后的URL
* @throws UtilException UnsupportedEncodingException
* @throws HutoolException UnsupportedEncodingException
*/
public static String encodeAll(final String url) {
return encodeAll(url, DEFAULT_CHARSET);
@ -53,9 +53,9 @@ public class URLEncoder {
* @param url URL
* @param charset 编码为null表示不编码
* @return 编码后的URL
* @throws UtilException UnsupportedEncodingException
* @throws HutoolException UnsupportedEncodingException
*/
public static String encodeAll(final String url, final Charset charset) throws UtilException {
public static String encodeAll(final String url, final Charset charset) throws HutoolException {
return RFC3986.UNRESERVED.encode(url, charset);
}

View File

@ -13,7 +13,7 @@
package org.dromara.hutool.core.net.url;
import org.dromara.hutool.core.classloader.ClassLoaderUtil;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.io.IORuntimeException;
import org.dromara.hutool.core.io.IoUtil;
import org.dromara.hutool.core.io.file.FileNameUtil;
@ -113,17 +113,17 @@ public class URLUtil {
* @param uri {@link URI}
* @return URL对象
* @see URI#toURL()
* @throws UtilException {@link MalformedURLException}包装URI格式有问题时抛出
* @throws HutoolException {@link MalformedURLException}包装URI格式有问题时抛出
* @since 5.7.21
*/
public static URL url(final URI uri) throws UtilException{
public static URL url(final URI uri) throws HutoolException {
if(null == uri){
return null;
}
try {
return uri.toURL();
} catch (final MalformedURLException e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}
@ -163,7 +163,7 @@ public class URLUtil {
try {
return new File(url).toURI().toURL();
} catch (final MalformedURLException ex2) {
throw new UtilException(e);
throw new HutoolException(e);
}
}
}
@ -209,7 +209,7 @@ public class URLUtil {
try {
return new URL(null, urlStr, handler);
} catch (final MalformedURLException e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}
@ -241,14 +241,14 @@ public class URLUtil {
*
* @param file URL对应的文件对象
* @return URL
* @throws UtilException MalformedURLException
* @throws HutoolException MalformedURLException
*/
public static URL getURL(final File file) {
Assert.notNull(file, "File is null !");
try {
return file.toURI().toURL();
} catch (final MalformedURLException e) {
throw new UtilException(e, "Error occured when get URL!");
throw new HutoolException(e, "Error occured when get URL!");
}
}
@ -257,7 +257,7 @@ public class URLUtil {
*
* @param files URL对应的文件对象
* @return URL
* @throws UtilException MalformedURLException
* @throws HutoolException MalformedURLException
*/
public static URL[] getURLs(final File... files) {
final URL[] urls = new URL[files.length];
@ -266,7 +266,7 @@ public class URLUtil {
urls[i] = files[i].toURI().toURL();
}
} catch (final MalformedURLException e) {
throw new UtilException(e, "Error occured when get URL!");
throw new HutoolException(e, "Error occured when get URL!");
}
return urls;
@ -287,7 +287,7 @@ public class URLUtil {
try {
return new URI(url.getProtocol(), url.getHost(), null, null);
} catch (final URISyntaxException e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}
@ -297,7 +297,7 @@ public class URLUtil {
* @param baseUrl 基准URL
* @param relativePath 相对URL
* @return 相对路径
* @throws UtilException MalformedURLException
* @throws HutoolException MalformedURLException
*/
public static String completeUrl(String baseUrl, final String relativePath) {
baseUrl = normalize(baseUrl, false);
@ -310,7 +310,7 @@ public class URLUtil {
final URL parseUrl = new URL(absoluteUrl, relativePath);
return parseUrl.toString();
} catch (final MalformedURLException e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}
@ -319,7 +319,7 @@ public class URLUtil {
*
* @param uriStr URI路径
* @return path
* @throws UtilException 包装URISyntaxException
* @throws HutoolException 包装URISyntaxException
*/
public static String getPath(final String uriStr) {
return toURI(uriStr).getPath();
@ -343,7 +343,7 @@ public class URLUtil {
try {
// URL对象的getPath方法对于包含中文或空格的问题
path = toURI(url).getPath();
} catch (final UtilException e) {
} catch (final HutoolException e) {
// ignore
}
return (null != path) ? path : url.getPath();
@ -354,9 +354,9 @@ public class URLUtil {
*
* @param url URL
* @return URI
* @throws UtilException 包装URISyntaxException
* @throws HutoolException 包装URISyntaxException
*/
public static URI toURI(final URL url) throws UtilException {
public static URI toURI(final URL url) throws HutoolException {
return toURI(url, false);
}
@ -366,10 +366,10 @@ public class URLUtil {
* @param url URL
* @param isEncode 是否编码参数中的特殊字符默认UTF-8编码
* @return URI
* @throws UtilException 包装URISyntaxException
* @throws HutoolException 包装URISyntaxException
* @since 4.6.9
*/
public static URI toURI(final URL url, final boolean isEncode) throws UtilException {
public static URI toURI(final URL url, final boolean isEncode) throws HutoolException {
if (null == url) {
return null;
}
@ -382,9 +382,9 @@ public class URLUtil {
*
* @param location 字符串路径
* @return URI
* @throws UtilException 包装URISyntaxException
* @throws HutoolException 包装URISyntaxException
*/
public static URI toURI(final String location) throws UtilException {
public static URI toURI(final String location) throws HutoolException {
return toURI(location, false);
}
@ -394,17 +394,17 @@ public class URLUtil {
* @param location 字符串路径
* @param isEncode 是否编码参数中的特殊字符默认UTF-8编码
* @return URI
* @throws UtilException 包装URISyntaxException
* @throws HutoolException 包装URISyntaxException
* @since 4.6.9
*/
public static URI toURI(String location, final boolean isEncode) throws UtilException {
public static URI toURI(String location, final boolean isEncode) throws HutoolException {
if (isEncode) {
location = RFC3986.PATH.encode(location, CharsetUtil.UTF_8);
}
try {
return new URI(StrUtil.trim(location));
} catch (final URISyntaxException e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.reflect;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.map.TripleTable;
import org.dromara.hutool.core.text.StrTrimer;
@ -126,9 +126,9 @@ public class ClassDescUtil {
*
* @param desc 类描述
* @return Class
* @throws UtilException 类没有找到
* @throws HutoolException 类没有找到
*/
public static Class<?> descToClass(final String desc) throws UtilException {
public static Class<?> descToClass(final String desc) throws HutoolException {
return descToClass(desc, true, null);
}
@ -143,9 +143,9 @@ public class ClassDescUtil {
* @param isInitialized 是否初始化类
* @param cl {@link ClassLoader}
* @return Class
* @throws UtilException 类没有找到
* @throws HutoolException 类没有找到
*/
public static Class<?> descToClass(String desc, final boolean isInitialized, final ClassLoader cl) throws UtilException {
public static Class<?> descToClass(String desc, final boolean isInitialized, final ClassLoader cl) throws HutoolException {
Assert.notNull(desc, "Name must not be null");
final char firstChar = desc.charAt(0);
final Class<?> clazz = PRIMITIVE_TABLE.getLeftByMiddle(firstChar);
@ -401,7 +401,7 @@ public class ClassDescUtil {
if (null != clazz) {
sb.append(PRIMITIVE_TABLE.getRightByLeft(clazz));
} else {
throw new UtilException("Unsupported primitive desc: {}", desc);
throw new HutoolException("Unsupported primitive desc: {}", desc);
}
} else {
sb.append(desc.substring(c + 1, desc.length() - 1).replace(CharUtil.SLASH, CharUtil.DOT));

View File

@ -15,7 +15,7 @@ package org.dromara.hutool.core.reflect;
import org.dromara.hutool.core.bean.NullWrapperBean;
import org.dromara.hutool.core.classloader.ClassLoaderUtil;
import org.dromara.hutool.core.convert.BasicType;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.io.file.FileUtil;
import org.dromara.hutool.core.io.resource.ResourceUtil;
import org.dromara.hutool.core.net.url.URLDecoder;
@ -27,6 +27,7 @@ import org.dromara.hutool.core.util.CharUtil;
import org.dromara.hutool.core.util.CharsetUtil;
import java.io.IOException;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.net.URI;
@ -307,7 +308,7 @@ public class ClassUtil {
try {
resources = ClassLoaderUtil.getClassLoader().getResources(packagePath);
} catch (final IOException e) {
throw new UtilException(e, "Loading classPath [{}] error!", packagePath);
throw new HutoolException(e, "Loading classPath [{}] error!", packagePath);
}
final Set<String> paths = new HashSet<>();
String path;
@ -435,16 +436,16 @@ public class ClassUtil {
*/
public static boolean isSimpleValueType(final Class<?> clazz) {
return isBasicType(clazz)
|| clazz.isEnum()
|| CharSequence.class.isAssignableFrom(clazz)
|| Number.class.isAssignableFrom(clazz)
|| Date.class.isAssignableFrom(clazz)
|| clazz.equals(URI.class)
|| clazz.equals(URL.class)
|| clazz.equals(Locale.class)
|| clazz.equals(Class.class)
// jdk8 date object
|| TemporalAccessor.class.isAssignableFrom(clazz);
|| clazz.isEnum()
|| CharSequence.class.isAssignableFrom(clazz)
|| Number.class.isAssignableFrom(clazz)
|| Date.class.isAssignableFrom(clazz)
|| clazz.equals(URI.class)
|| clazz.equals(URL.class)
|| clazz.equals(Locale.class)
|| clazz.equals(Class.class)
// jdk8 date object
|| TemporalAccessor.class.isAssignableFrom(clazz);
}
/**
@ -479,6 +480,17 @@ public class ClassUtil {
}
}
/**
* 给定类是否实现了序列化接口{@link Serializable}
*
* @param clazz
* @return 是否实现序列化接口{@link Serializable}
* @since 6.0.0
*/
public static boolean isSerializable(final Class<?> clazz) {
return Serializable.class.isAssignableFrom(clazz);
}
/**
* 是否为标准的类<br>
* 这个类必须
@ -497,13 +509,13 @@ public class ClassUtil {
*/
public static boolean isNormalClass(final Class<?> clazz) {
return null != clazz
&& !clazz.isInterface()
&& !ModifierUtil.isAbstract(clazz)
&& !clazz.isEnum()
&& !clazz.isArray()
&& !clazz.isAnnotation()
&& !clazz.isSynthetic()
&& !clazz.isPrimitive();
&& !clazz.isInterface()
&& !ModifierUtil.isAbstract(clazz)
&& !clazz.isEnum()
&& !clazz.isArray()
&& !clazz.isAnnotation()
&& !clazz.isSynthetic()
&& !clazz.isPrimitive();
}
/**
@ -660,8 +672,8 @@ public class ClassUtil {
}
final String objectPackageName = objectPackage.getName();
return objectPackageName.startsWith("java.")
|| objectPackageName.startsWith("javax.")
|| clazz.getClassLoader() == null;
|| objectPackageName.startsWith("javax.")
|| clazz.getClassLoader() == null;
}
/**
@ -742,14 +754,14 @@ public class ClassUtil {
* <li>自动查找内部类如java.lang.Thread.State =java.lang.Thread$State</li>
* </ul>
*
* @param name 类名
* @param name 类名
* @param isInitialized 是否初始化
* @param loader {@link ClassLoader}{@code null}表示默认
* @param loader {@link ClassLoader}{@code null}表示默认
* @return 指定名称对应的类如果不存在类返回{@code null}
* @see Class#forName(String, boolean, ClassLoader)
*/
public static Class<?> forName(String name, final boolean isInitialized, ClassLoader loader) {
if(null == loader){
if (null == loader) {
loader = ClassLoaderUtil.getClassLoader();
}
name = name.replace(CharUtil.SLASH, CharUtil.DOT);
@ -761,7 +773,7 @@ public class ClassUtil {
// 尝试获取内部类例如java.lang.Thread.State =java.lang.Thread$State
final Class<?> clazz = forNameInnerClass(name, isInitialized, loader);
if (null == clazz) {
throw new UtilException(ex);
throw new HutoolException(ex);
}
return clazz;
}

View File

@ -12,12 +12,13 @@
package org.dromara.hutool.core.reflect;
import org.dromara.hutool.core.array.ArrayUtil;
import org.dromara.hutool.core.classloader.ClassLoaderUtil;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.map.WeakConcurrentMap;
import org.dromara.hutool.core.reflect.lookup.LookupUtil;
import java.lang.invoke.MethodHandle;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.util.*;
@ -95,9 +96,9 @@ public class ConstructorUtil {
* @param <T> 对象类型
* @param clazz 类名
* @return 对象
* @throws UtilException 包装各类异常
* @throws HutoolException 包装各类异常
*/
public static <T> T newInstance(final String clazz) throws UtilException {
public static <T> T newInstance(final String clazz) throws HutoolException {
return newInstance(ClassLoaderUtil.loadClass(clazz));
}
@ -108,31 +109,12 @@ public class ConstructorUtil {
* @param clazz
* @param params 构造函数参数
* @return 对象
* @throws UtilException 包装各类异常
* @throws HutoolException 包装各类异常
*/
public static <T> T newInstance(final Class<T> clazz, final Object... params) throws UtilException {
if (ArrayUtil.isEmpty(params)) {
final Constructor<T> constructor = getConstructor(clazz);
if (null == constructor) {
throw new UtilException("No constructor for [{}]", clazz);
}
try {
return constructor.newInstance();
} catch (final Exception e) {
throw new UtilException(e, "Instance class [{}] error!", clazz);
}
}
public static <T> T newInstance(final Class<T> clazz, final Object... params) throws HutoolException {
final Class<?>[] paramTypes = ClassUtil.getClasses(params);
final Constructor<T> constructor = getConstructor(clazz, paramTypes);
if (null == constructor) {
throw new UtilException("No Constructor matched for parameter types: {}", new Object[]{paramTypes});
}
try {
return constructor.newInstance(params);
} catch (final Exception e) {
throw new UtilException(e, "Instance class [{}] error!", clazz);
}
final MethodHandle constructor = LookupUtil.findConstructor(clazz, paramTypes);
return MethodHandleUtil.invokeHandle(constructor, params);
}
/**

View File

@ -14,7 +14,7 @@ package org.dromara.hutool.core.reflect;
import org.dromara.hutool.core.annotation.Alias;
import org.dromara.hutool.core.convert.Convert;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.map.MapUtil;
import org.dromara.hutool.core.map.WeakConcurrentMap;
@ -180,9 +180,9 @@ public class FieldUtil {
* @param obj 对象如果static字段此处为类
* @param fieldName 字段名
* @return 字段值
* @throws UtilException 包装IllegalAccessException异常
* @throws HutoolException 包装IllegalAccessException异常
*/
public static Object getFieldValue(final Object obj, final String fieldName) throws UtilException {
public static Object getFieldValue(final Object obj, final String fieldName) throws HutoolException {
if (null == obj || StrUtil.isBlank(fieldName)) {
return null;
}
@ -194,10 +194,10 @@ public class FieldUtil {
*
* @param field 字段
* @return 字段值
* @throws UtilException 包装IllegalAccessException异常
* @throws HutoolException 包装IllegalAccessException异常
* @since 5.1.0
*/
public static Object getStaticFieldValue(final Field field) throws UtilException {
public static Object getStaticFieldValue(final Field field) throws HutoolException {
return getFieldValue(null, field);
}
@ -207,9 +207,9 @@ public class FieldUtil {
* @param obj 对象static字段则此字段为null
* @param field 字段
* @return 字段值
* @throws UtilException 包装IllegalAccessException异常
* @throws HutoolException 包装IllegalAccessException异常
*/
public static Object getFieldValue(Object obj, final Field field) throws UtilException {
public static Object getFieldValue(Object obj, final Field field) throws HutoolException {
if (null == field) {
return null;
}
@ -223,7 +223,7 @@ public class FieldUtil {
try {
result = field.get(obj);
} catch (final IllegalAccessException e) {
throw new UtilException(e, "IllegalAccess for {}.{}", field.getDeclaringClass(), field.getName());
throw new HutoolException(e, "IllegalAccess for {}.{}", field.getDeclaringClass(), field.getName());
}
return result;
}
@ -255,9 +255,9 @@ public class FieldUtil {
* @param obj 对象,static字段则此处传Class
* @param fieldName 字段名
* @param value 值类型必须与字段类型匹配不会自动转换对象类型
* @throws UtilException 包装IllegalAccessException异常
* @throws HutoolException 包装IllegalAccessException异常
*/
public static void setFieldValue(final Object obj, final String fieldName, final Object value) throws UtilException {
public static void setFieldValue(final Object obj, final String fieldName, final Object value) throws HutoolException {
Assert.notNull(obj);
Assert.notBlank(fieldName);
@ -271,9 +271,9 @@ public class FieldUtil {
*
* @param field 字段
* @param value 值类型必须与字段类型匹配不会自动转换对象类型
* @throws UtilException UtilException 包装IllegalAccessException异常
* @throws HutoolException UtilException 包装IllegalAccessException异常
*/
public static void setStaticFieldValue(final Field field, final Object value) throws UtilException {
public static void setStaticFieldValue(final Field field, final Object value) throws HutoolException {
setFieldValue(null, field, value);
}
@ -283,9 +283,9 @@ public class FieldUtil {
* @param obj 对象如果是static字段此参数为null
* @param field 字段
* @param value 类型不匹配会自动转换对象类型
* @throws UtilException UtilException 包装IllegalAccessException异常
* @throws HutoolException UtilException 包装IllegalAccessException异常
*/
public static void setFieldValue(final Object obj, final Field field, Object value) throws UtilException {
public static void setFieldValue(final Object obj, final Field field, Object value) throws HutoolException {
Assert.notNull(field, "Field in [{}] not exist !", obj);
// 值类型检查和转换
@ -312,14 +312,14 @@ public class FieldUtil {
* @param obj 对象如果是static字段此参数为null
* @param field 字段
* @param value 值类型必须与字段类型匹配
* @throws UtilException UtilException 包装IllegalAccessException异常
* @throws HutoolException UtilException 包装IllegalAccessException异常
*/
public static void setFieldValueExact(final Object obj, final Field field, final Object value) throws UtilException {
public static void setFieldValueExact(final Object obj, final Field field, final Object value) throws HutoolException {
ReflectUtil.setAccessible(field);
try {
field.set(obj instanceof Class ? null : obj, value);
} catch (final IllegalAccessException e) {
throw new UtilException(e, "IllegalAccess for [{}.{}]", null == obj ? field.getDeclaringClass() : obj, field.getName());
throw new HutoolException(e, "IllegalAccess for [{}.{}]", null == obj ? field.getDeclaringClass() : obj, field.getName());
}
}

View File

@ -12,12 +12,13 @@
package org.dromara.hutool.core.reflect;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.bean.NullWrapperBean;
import org.dromara.hutool.core.convert.Convert;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.reflect.lookup.LookupUtil;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Method;
/**
@ -50,82 +51,12 @@ public class MethodHandleUtil {
@SuppressWarnings("unchecked")
public static <T> T invokeHandle(final MethodHandle methodHandle, final Object... args) {
try {
return (T) methodHandle.invoke(args);
return (T) methodHandle.invokeWithArguments(args);
} catch (final Throwable e) {
throw new RuntimeException(e);
}
}
/**
* 执行接口或对象中的方法
*
* @param <T> 返回结果类型
* @param obj 接口的子对象或代理对象
* @param method 方法
* @param args 参数
* @return 结果
*/
public static <T> T invoke(final Object obj, final Method method, final Object... args) {
return invoke(false, obj, method, args);
}
/**
* 执行接口或对象中的特殊方法privatestatic等<br>
*
* <pre class="code">
* interface Duck {
* default String quack() {
* return "Quack";
* }
* }
* Duck duck = (Duck) Proxy.newProxyInstance(
* ClassLoaderUtil.getClassLoader(),
* new Class[] { Duck.class },
* MethodHandleUtil::invokeDefault);
* </pre>
*
* @param <T> 返回结果类型
* @param obj 接口的子对象或代理对象
* @param methodName 方法名称
* @param args 参数
* @return 结果
*/
public static <T> T invokeSpecial(final Object obj, final String methodName, final Object... args) {
Assert.notNull(obj, "Object to get method must be not null!");
Assert.notBlank(methodName, "Method name must be not blank!");
final Method method = MethodUtil.getMethodOfObj(obj, methodName, args);
if (null == method) {
throw new UtilException("No such method: [{}] from [{}]", methodName, obj.getClass());
}
return invokeSpecial(obj, method, args);
}
/**
* 执行接口或对象中的特殊方法privatestatic等<br>
*
* <pre class="code">
* interface Duck {
* default String quack() {
* return "Quack";
* }
* }
* Duck duck = (Duck) Proxy.newProxyInstance(
* ClassLoaderUtil.getClassLoader(),
* new Class[] { Duck.class },
* MethodHandleUtil::invoke);
* </pre>
*
* @param <T> 返回结果类型
* @param obj 接口的子对象或代理对象
* @param method 方法
* @param args 参数
* @return 结果
*/
public static <T> T invokeSpecial(final Object obj, final Method method, final Object... args) {
return invoke(true, obj, method, args);
}
/**
* 执行接口或对象中的方法<br>
*
@ -142,26 +73,93 @@ public class MethodHandleUtil {
* </pre>
*
* @param <T> 返回结果类型
* @param isSpecial 是否为特殊方法privatestatic等
* @param obj 接口的子对象或代理对象
* @param method 方法
* @param args 参数自动根据{@link Method}定义类型转换
* @return 结果
* @throws HutoolException 执行异常包装
*/
public static <T> T invoke(final Object obj, final Method method, final Object... args) throws HutoolException{
Assert.notNull(method, "Method must be not null!");
return invokeExact(obj, method, actualArgs(method, args));
}
/**
* 执行接口或对象中的方法参数类型不做转换必须与方法参数类型完全匹配<br>
*
* <pre class="code">
* interface Duck {
* default String quack() {
* return "Quack";
* }
* }
* Duck duck = (Duck) Proxy.newProxyInstance(
* ClassLoaderUtil.getClassLoader(),
* new Class[] { Duck.class },
* MethodHandleUtil::invoke);
* </pre>
*
* @param <T> 返回结果类型
* @param obj 接口的子对象或代理对象
* @param method 方法
* @param args 参数
* @return 结果
* @throws HutoolException 执行异常包装
*/
@SuppressWarnings("unchecked")
public static <T> T invoke(final boolean isSpecial, final Object obj, final Method method, final Object... args) {
public static <T> T invokeExact(final Object obj, final Method method, final Object... args) throws HutoolException{
Assert.notNull(method, "Method must be not null!");
final Class<?> declaringClass = method.getDeclaringClass();
final MethodHandles.Lookup lookup = LookupUtil.lookup(declaringClass);
try {
MethodHandle handle = isSpecial ? lookup.unreflectSpecial(method, declaringClass)
: lookup.unreflect(method);
MethodHandle handle = LookupUtil.unreflectMethod(method);
if (null != obj) {
handle = handle.bindTo(obj);
}
return (T) handle.invokeWithArguments(args);
} catch (final Throwable e) {
throw new UtilException(e);
if(e instanceof RuntimeException){
throw (RuntimeException)e;
}
throw new HutoolException(e);
}
}
/**
* 检查用户传入参数
* <ul>
* <li>1忽略多余的参数</li>
* <li>2参数不够补齐默认值</li>
* <li>3通过NullWrapperBean传递的参数,会直接赋值null</li>
* <li>4传入参数为null但是目标参数类型为原始类型做转换</li>
* <li>5传入参数类型不对应尝试转换类型</li>
* </ul>
*
* @param method 方法
* @param args 参数
* @return 实际的参数数组
*/
private static Object[] actualArgs(final Method method, final Object[] args) {
final Class<?>[] parameterTypes = method.getParameterTypes();
final Object[] actualArgs = new Object[parameterTypes.length];
if (null != args) {
for (int i = 0; i < actualArgs.length; i++) {
if (i >= args.length || null == args[i]) {
// 越界或者空值
actualArgs[i] = ClassUtil.getDefaultValue(parameterTypes[i]);
} else if (args[i] instanceof NullWrapperBean) {
//如果是通过NullWrapperBean传递的null参数,直接赋值null
actualArgs[i] = null;
} else if (!parameterTypes[i].isAssignableFrom(args[i].getClass())) {
//对于类型不同的字段尝试转换转换失败则使用原对象类型
final Object targetValue = Convert.convert(parameterTypes[i], args[i], args[i]);
if (null != targetValue) {
actualArgs[i] = targetValue;
}
} else {
actualArgs[i] = args[i];
}
}
}
return actualArgs;
}
}

View File

@ -0,0 +1,48 @@
/*
* Copyright (c) 2023 looly(loolly@aliyun.com)
* Hutool is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
package org.dromara.hutool.core.reflect;
import java.lang.invoke.MethodType;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.lang.reflect.Method;
/**
* {@link MethodType}相关工具类
*
* @author looly
* @since 6.0.0
*/
public class MethodTypeUtil {
/**
* 获取指定{@link Executable}{@link MethodType}<br>
* 此方法主要是读取方法或构造中的方法列表主要为
* <ul>
* <li>方法[返回类型, 参数1类型, 参数2类型, ...]</li>
* <li>构造[构造对应类类型, 参数1类型, 参数2类型, ...]</li>
* </ul>
*
* @param executable 方法或构造
* @return {@link MethodType}
*/
public static MethodType methodType(final Executable executable) {
if (executable instanceof Method) {
final Method method = (Method) executable;
return MethodType.methodType(method.getReturnType(), method.getDeclaringClass(), method.getParameterTypes());
} else {
final Constructor<?> constructor = (Constructor<?>) executable;
return MethodType.methodType(constructor.getDeclaringClass(), constructor.getParameterTypes());
}
}
}

View File

@ -12,21 +12,18 @@
package org.dromara.hutool.core.reflect;
import org.dromara.hutool.core.array.ArrayUtil;
import org.dromara.hutool.core.bean.NullWrapperBean;
import org.dromara.hutool.core.classloader.ClassLoaderUtil;
import org.dromara.hutool.core.collection.set.SetUtil;
import org.dromara.hutool.core.collection.set.UniqueKeySet;
import org.dromara.hutool.core.convert.Convert;
import org.dromara.hutool.core.exceptions.InvocationTargetRuntimeException;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.lang.Singleton;
import org.dromara.hutool.core.map.WeakConcurrentMap;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.array.ArrayUtil;
import org.dromara.hutool.core.util.BooleanUtil;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.function.Predicate;
@ -568,9 +565,9 @@ public class MethodUtil {
* @param method 方法对象方法或static方法都可
* @param args 参数对象
* @return 结果
* @throws UtilException 多种异常包装
* @throws HutoolException 多种异常包装
*/
public static <T> T invokeStatic(final Method method, final Object... args) throws UtilException {
public static <T> T invokeStatic(final Method method, final Object... args) throws HutoolException {
return invoke(null, method, args);
}
@ -588,9 +585,9 @@ public class MethodUtil {
* @param method 方法对象方法或static方法都可
* @param args 参数对象
* @return 结果
* @throws UtilException 一些列异常的包装
* @throws HutoolException 一些列异常的包装
*/
public static <T> T invokeWithCheck(final Object obj, final Method method, final Object... args) throws UtilException {
public static <T> T invokeWithCheck(final Object obj, final Method method, final Object... args) throws HutoolException {
final Class<?>[] types = method.getParameterTypes();
if (null != args) {
Assert.isTrue(args.length == types.length, "Params length [{}] is not fit for param length [{}] of method !", args.length, types.length);
@ -624,49 +621,11 @@ public class MethodUtil {
* @param method 方法对象方法或static方法都可
* @param args 参数对象
* @return 结果
* @throws UtilException 一些列异常的包装
* @throws HutoolException 一些列异常的包装
* @see MethodHandleUtil#invoke(Object, Method, Object...)
*/
public static <T> T invoke(final Object obj, final Method method, final Object... args) throws UtilException {
try {
return invokeRaw(obj, method, args);
} catch (final InvocationTargetException e) {
throw new InvocationTargetRuntimeException(e);
} catch (final IllegalAccessException e) {
throw new UtilException(e);
}
}
/**
* 执行方法
*
* <p>
* 对于用户传入参数会做必要检查包括
*
* <pre>
* 1忽略多余的参数
* 2参数不够补齐默认值
* 3传入参数为null但是目标参数类型为原始类型做转换
* </pre>
*
* @param <T> 返回对象类型
* @param obj 对象如果执行静态方法此值为{@code null}
* @param method 方法对象方法或static方法都可
* @param args 参数对象
* @return 结果
* @throws InvocationTargetException 目标方法执行异常
* @throws IllegalAccessException 访问权限异常
*/
@SuppressWarnings("unchecked")
public static <T> T invokeRaw(final Object obj, final Method method, final Object... args) throws InvocationTargetException, IllegalAccessException {
ReflectUtil.setAccessible(method);
if (method.isDefault()) {
// 当方法是default方法时尤其对象是代理对象需使用句柄方式执行
// 代理对象情况下调用method.invoke会导致循环引用执行最终栈溢出
return MethodHandleUtil.invokeSpecial(obj, method, args);
}
return (T) method.invoke(ModifierUtil.isStatic(method) ? null : obj, actualArgs(method, args));
public static <T> T invoke(final Object obj, final Method method, final Object... args) throws HutoolException {
return MethodHandleUtil.invoke(obj, method, args);
}
/**
@ -678,17 +637,17 @@ public class MethodUtil {
* @param methodName 方法名
* @param args 参数列表
* @return 执行结果
* @throws UtilException IllegalAccessException包装
* @throws HutoolException IllegalAccessException包装
* @see NullWrapperBean
* @since 3.1.2
*/
public static <T> T invoke(final Object obj, final String methodName, final Object... args) throws UtilException {
public static <T> T invoke(final Object obj, final String methodName, final Object... args) throws HutoolException {
Assert.notNull(obj, "Object to get method must be not null!");
Assert.notBlank(methodName, "Method name must be not blank!");
final Method method = getMethodOfObj(obj, methodName, args);
if (null == method) {
throw new UtilException("No such method: [{}] from [{}]", methodName, obj.getClass());
throw new HutoolException("No such method: [{}] from [{}]", methodName, obj.getClass());
}
return invoke(obj, method, args);
}
@ -721,7 +680,7 @@ public class MethodUtil {
*/
public static <T> T invoke(final String classNameWithMethodName, final boolean isSingleton, final Object... args) {
if (StrUtil.isBlank(classNameWithMethodName)) {
throw new UtilException("Blank classNameDotMethodName!");
throw new HutoolException("Blank classNameDotMethodName!");
}
int splitIndex = classNameWithMethodName.lastIndexOf('#');
@ -729,7 +688,7 @@ public class MethodUtil {
splitIndex = classNameWithMethodName.lastIndexOf('.');
}
if (splitIndex <= 0) {
throw new UtilException("Invalid classNameWithMethodName [{}]!", classNameWithMethodName);
throw new HutoolException("Invalid classNameWithMethodName [{}]!", classNameWithMethodName);
}
final String className = classNameWithMethodName.substring(0, splitIndex);
@ -769,17 +728,17 @@ public class MethodUtil {
public static <T> T invoke(final String className, final String methodName, final boolean isSingleton, final Object... args) {
final Class<?> clazz = ClassLoaderUtil.loadClass(className);
try {
final Method method = MethodUtil.getMethod(clazz, methodName, ClassUtil.getClasses(args));
final Method method = getMethod(clazz, methodName, ClassUtil.getClasses(args));
if (null == method) {
throw new NoSuchMethodException(StrUtil.format("No such method: [{}]", methodName));
}
if (ModifierUtil.isStatic(method)) {
return MethodUtil.invoke(null, method, args);
return invoke(null, method, args);
} else {
return MethodUtil.invoke(isSingleton ? Singleton.get(clazz) : clazz.newInstance(), method, args);
return invoke(isSingleton ? Singleton.get(clazz) : ConstructorUtil.newInstance(clazz), method, args);
}
} catch (final Exception e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}
@ -825,44 +784,4 @@ public class MethodUtil {
}
return result;
}
/**
* 检查用户传入参数
* <ul>
* <li>1忽略多余的参数</li>
* <li>2参数不够补齐默认值</li>
* <li>3通过NullWrapperBean传递的参数,会直接赋值null</li>
* <li>4传入参数为null但是目标参数类型为原始类型做转换</li>
* <li>5传入参数类型不对应尝试转换类型</li>
* </ul>
*
* @param method 方法
* @param args 参数
* @return 实际的参数数组
*/
private static Object[] actualArgs(final Method method, final Object[] args) {
final Class<?>[] parameterTypes = method.getParameterTypes();
final Object[] actualArgs = new Object[parameterTypes.length];
if (null != args) {
for (int i = 0; i < actualArgs.length; i++) {
if (i >= args.length || null == args[i]) {
// 越界或者空值
actualArgs[i] = ClassUtil.getDefaultValue(parameterTypes[i]);
} else if (args[i] instanceof NullWrapperBean) {
//如果是通过NullWrapperBean传递的null参数,直接赋值null
actualArgs[i] = null;
} else if (!parameterTypes[i].isAssignableFrom(args[i].getClass())) {
//对于类型不同的字段尝试转换转换失败则使用原对象类型
final Object targetValue = Convert.convertQuietly(parameterTypes[i], args[i], args[i]);
if (null != targetValue) {
actualArgs[i] = targetValue;
}
} else {
actualArgs[i] = args[i];
}
}
}
return actualArgs;
}
}

View File

@ -13,10 +13,11 @@
package org.dromara.hutool.core.reflect;
import org.dromara.hutool.core.array.ArrayUtil;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
@ -132,6 +133,17 @@ public class ModifierUtil {
return 0 != (member.getModifiers() & modifiersToInt(modifierTypes));
}
/**
* 提供的方法是否为default方法
*
* @param method 方法
* @return 是否为default方法
* @since 6.0.0
*/
public static boolean isDefault(final Method method) {
return method.isDefault();
}
/**
* 是否是public成员可检测包括构造字段和方法
*
@ -275,7 +287,7 @@ public class ModifierUtil {
* <p>JDK9+此方法抛出NoSuchFieldException异常原因是除非开放否则模块外无法访问属性</p>
*
* @param field 被修改的field不可以为空
* @throws UtilException IllegalAccessException等异常包装
* @throws HutoolException IllegalAccessException等异常包装
* @author dazer
* @since 5.8.8
*/
@ -289,10 +301,10 @@ public class ModifierUtil {
//去除final修饰符的影响将字段设为可修改的
final Field modifiersField;
try{
try {
modifiersField = Field.class.getDeclaredField("modifiers");
} catch (final NoSuchFieldException e){
throw new UtilException(e, "Field [modifiers] not exist!");
} catch (final NoSuchFieldException e) {
throw new HutoolException(e, "Field [modifiers] not exist!");
}
try {
@ -303,7 +315,7 @@ public class ModifierUtil {
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
} catch (final IllegalAccessException e) {
//内部工具类基本不抛出异常
throw new UtilException(e, "IllegalAccess for [{}.{}]", field.getDeclaringClass(), field.getName());
throw new HutoolException(e, "IllegalAccess for [{}.{}]", field.getDeclaringClass(), field.getName());
}
}
//-------------------------------------------------------------------------------------------------------- Private method start

View File

@ -12,8 +12,10 @@
package org.dromara.hutool.core.reflect.lookup;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.lang.caller.CallerUtil;
import org.dromara.hutool.core.reflect.ConstructorUtil;
import org.dromara.hutool.core.reflect.ModifierUtil;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.util.JdkUtil;
@ -80,20 +82,46 @@ public class LookupUtil {
*
* @param methodOrConstructor {@link Method}或者{@link Constructor}
* @return 方法句柄{@link MethodHandle}
* @throws HutoolException {@link IllegalAccessException} 包装
*/
public static MethodHandle unreflect(final Member methodOrConstructor) {
public static MethodHandle unreflect(final Member methodOrConstructor) throws HutoolException {
try {
if (methodOrConstructor instanceof Method) {
return lookup().unreflect((Method) methodOrConstructor);
return unreflectMethod((Method) methodOrConstructor);
} else {
return lookup().unreflectConstructor((Constructor<?>) methodOrConstructor);
}
} catch (final IllegalAccessException e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}
/**
* {@link Method} 转换为方法句柄{@link MethodHandle}
*
* @param method {@link Method}
* @return {@link MethodHandles}
* @throws IllegalAccessException 无权访问
*/
public static MethodHandle unreflectMethod(final Method method) throws IllegalAccessException {
final Class<?> caller = method.getDeclaringClass();
final MethodHandles.Lookup lookup = lookup(caller);
if (ModifierUtil.isDefault(method)) {
// 当方法是default方法时尤其对象是代理对象需使用句柄方式执行
// 代理对象情况下调用method.invoke会导致循环引用执行最终栈溢出
return lookup.unreflectSpecial(method, caller);
}
try {
return lookup.unreflect(method);
} catch (final Exception ignore) {
// 某些情况下无权限执行方法则尝试执行特殊方法
return lookup.unreflectSpecial(method, caller);
}
}
// region ----- findMethod
/**
* 查找指定方法的方法句柄<br>
* 此方法只会查找
@ -157,7 +185,7 @@ public class LookupUtil {
} catch (final NoSuchMethodException ignore) {
//ignore
} catch (final IllegalAccessException e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}
@ -166,6 +194,7 @@ public class LookupUtil {
// endregion
// region ----- findConstructor
/**
* 查找指定的构造方法
*
@ -174,6 +203,21 @@ public class LookupUtil {
* @return 构造方法句柄
*/
public static MethodHandle findConstructor(final Class<?> callerClass, final Class<?>... argTypes) {
final Constructor<?> constructor = ConstructorUtil.getConstructor(callerClass, argTypes);
if(null != constructor){
return LookupUtil.unreflect(constructor);
}
return null;
}
/**
* 查找指定的构造方法给定的参数类型必须完全匹配不能有拆装箱或继承关系等/
*
* @param callerClass
* @param argTypes 参数类型列表完全匹配
* @return 构造方法句柄
*/
public static MethodHandle findConstructorExact(final Class<?> callerClass, final Class<?>... argTypes) {
return findConstructor(callerClass, MethodType.methodType(void.class, argTypes));
}
@ -191,7 +235,7 @@ public class LookupUtil {
} catch (final NoSuchMethodException e) {
return null;
} catch (final IllegalAccessException e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}
// endregion

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.reflect.lookup;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.InvocationTargetException;
@ -42,12 +42,13 @@ public class MethodLookupFactory implements LookupFactory {
public MethodHandles.Lookup lookup(final Class<?> callerClass) {
try {
return (MethodHandles.Lookup) privateLookupInMethod.invoke(MethodHandles.class, callerClass, MethodHandles.lookup());
} catch (final IllegalAccessException | InvocationTargetException e) {
throw new UtilException(e);
} catch (final IllegalAccessException e) {
throw new HutoolException(e);
} catch (final InvocationTargetException e) {
throw new HutoolException(e.getTargetException());
}
}
@SuppressWarnings("JavaReflectionMemberAccess")
private static Method createJdk9PrivateLookupInMethod() {
try {
return MethodHandles.class.getMethod("privateLookupIn", Class.class, MethodHandles.Lookup.class);

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.text.placeholder;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.text.StrChecker;
import org.dromara.hutool.core.util.CharUtil;
@ -154,7 +154,7 @@ public class PlaceholderParser implements UnaryOperator<String> {
// 未能找到结束符号说明匹配异常
if (end == -1) {
throw new UtilException("\"{}\" 中字符下标 {} 处的开始符没有找到对应的结束符", text, openCursor);
throw new HutoolException("\"{}\" 中字符下标 {} 处的开始符没有找到对应的结束符", text, openCursor);
}
// 找到结束符号将开始到结束符号之间的字符串替换为指定表达式
else {

View File

@ -3,7 +3,7 @@ package org.dromara.hutool.core.text.placeholder;
import org.dromara.hutool.core.array.ArrayUtil;
import org.dromara.hutool.core.collection.CollUtil;
import org.dromara.hutool.core.collection.ListUtil;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.text.CharPool;
import org.dromara.hutool.core.text.StrUtil;
@ -200,7 +200,7 @@ public abstract class StrTemplate {
} else {
// 有两个紧密相连的占位符无法正确地拆分变量值
if (hasPlaceholder) {
throw new UtilException("There are two closely related placeholders that cannot be split properly!");
throw new HutoolException("There are two closely related placeholders that cannot be split properly!");
}
hasPlaceholder = true;
}
@ -350,9 +350,9 @@ public abstract class StrTemplate {
} else if (FORMAT_MISSING_KEY_PRINT_VARIABLE_NAME.contains(features)) {
return segment.getPlaceholder();
} else if (FORMAT_MISSING_KEY_THROWS.contains(features)) {
throw new UtilException("There is no value associated with key: '" + segment.getPlaceholder() + "'");
throw new HutoolException("There is no value associated with key: '" + segment.getPlaceholder() + "'");
}
throw new UtilException("There is no value associated with key: '" + segment.getPlaceholder() +
throw new HutoolException("There is no value associated with key: '" + segment.getPlaceholder() +
"'. You should define some Feature for missing key when building.");
}
@ -373,7 +373,7 @@ public abstract class StrTemplate {
} else if (FORMAT_NULL_VALUE_TO_DEFAULT_VALUE.contains(features)) {
return getDefaultValue(segment);
}
throw new UtilException("There is a NULL value cannot resolve. You should define a Feature for null value when building or filter null value.");
throw new HutoolException("There is a NULL value cannot resolve. You should define a Feature for null value when building or filter null value.");
}
// endregion
@ -434,7 +434,7 @@ public abstract class StrTemplate {
} else {
// 有两个紧密相连的占位符无法正确地拆分变量值
if (placeholderSegment != null) {
throw new UtilException("There are two closely related placeholders that cannot be split properly!");
throw new HutoolException("There are two closely related placeholders that cannot be split properly!");
}
placeholderSegment = (AbstractPlaceholderSegment) segment;
}
@ -587,7 +587,7 @@ public abstract class StrTemplate {
} else if (globalDefaultValueHandler != null) {
return StrUtil.utf8Str(globalDefaultValueHandler.apply(segment.getPlaceholder()));
}
throw new UtilException("There is no default value for key: '" + segment.getPlaceholder() +
throw new HutoolException("There is no default value for key: '" + segment.getPlaceholder() +
"'. You should define a 'defaultValue' or 'defaultValueHandler' or 'globalDefaultValueHandler' when building.");
}

View File

@ -6,7 +6,7 @@ import org.dromara.hutool.core.bean.BeanUtil;
import org.dromara.hutool.core.collection.CollUtil;
import org.dromara.hutool.core.collection.ListUtil;
import org.dromara.hutool.core.convert.Convert;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.func.LambdaUtil;
import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.math.NumberUtil;
@ -149,7 +149,7 @@ public class NamedPlaceholderStrTemplate extends StrTemplate {
// 未能找到结束符号说明匹配异常
if (end == -1) {
throw new UtilException("\"{}\" 中字符下标 {} 处的开始符没有找到对应的结束符", template, openCursor);
throw new HutoolException("\"{}\" 中字符下标 {} 处的开始符没有找到对应的结束符", template, openCursor);
}
// 找到结束符号开始到结束符号 之间的字符串 就是占位变量
else {

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.thread;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
@ -78,7 +78,7 @@ public class GlobalThreadPool {
try {
executor.execute(runnable);
} catch (final Exception e) {
throw new UtilException(e, "Exception when running task!");
throw new HutoolException(e, "Exception when running task!");
}
}

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.thread;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import java.io.Closeable;
import java.util.LinkedHashSet;
@ -151,7 +151,7 @@ public class SyncFinisher implements Closeable {
try {
this.endLatch.await();
} catch (final InterruptedException e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}
}
@ -226,7 +226,7 @@ public class SyncFinisher implements Closeable {
try {
beginLatch.await();
} catch (final InterruptedException e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}
try {

View File

@ -13,7 +13,7 @@
package org.dromara.hutool.core.util;
import org.dromara.hutool.core.convert.Convert;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.map.MapUtil;
import javax.naming.InitialContext;
@ -50,7 +50,7 @@ public class JNDIUtil {
}
return new InitialDirContext(Convert.convert(Hashtable.class, environment));
} catch (final NamingException e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}
@ -67,7 +67,7 @@ public class JNDIUtil {
}
return new InitialContext(Convert.convert(Hashtable.class, environment));
} catch (final NamingException e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}
@ -83,7 +83,7 @@ public class JNDIUtil {
try {
return createInitialDirContext(null).getAttributes(uri, attrIds);
} catch (final NamingException e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}
}

View File

@ -16,7 +16,7 @@ import org.dromara.hutool.core.array.ArrayUtil;
import org.dromara.hutool.core.collection.CollUtil;
import org.dromara.hutool.core.collection.iter.IterUtil;
import org.dromara.hutool.core.convert.Convert;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.io.SerializeUtil;
import org.dromara.hutool.core.map.MapUtil;
import org.dromara.hutool.core.math.NumberUtil;
@ -394,7 +394,7 @@ public class ObjUtil {
* @param <T> 对象类型
* @param obj 被克隆对象
* @return 克隆后的对象
* @throws UtilException IO异常和ClassNotFoundException封装
* @throws HutoolException IO异常和ClassNotFoundException封装
* @see SerializeUtil#clone(Object)
*/
public static <T> T cloneByStream(final T obj) {

View File

@ -18,7 +18,7 @@ import org.dromara.hutool.core.collection.ListUtil;
import org.dromara.hutool.core.date.DateField;
import org.dromara.hutool.core.date.DateTime;
import org.dromara.hutool.core.date.DateUtil;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.lang.Assert;
import org.dromara.hutool.core.lang.WeightRandom;
import org.dromara.hutool.core.lang.WeightRandom.WeightObj;
@ -132,7 +132,7 @@ public class RandomUtil {
try {
random = SecureRandom.getInstance("SHA1PRNG");
} catch (final NoSuchAlgorithmException e) {
throw new UtilException(e);
throw new HutoolException(e);
}
if (null != seed) {
random.setSeed(seed);
@ -151,7 +151,7 @@ public class RandomUtil {
try {
return SecureRandom.getInstanceStrong();
} catch (final NoSuchAlgorithmException e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}

View File

@ -13,7 +13,7 @@
package org.dromara.hutool.core.util;
import org.dromara.hutool.core.array.ArrayUtil;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.io.IORuntimeException;
import org.dromara.hutool.core.io.IoUtil;
import org.dromara.hutool.core.lang.id.Pid;
@ -309,10 +309,10 @@ public class RuntimeUtil {
* 获取当前进程ID首先获取进程名称读取@前的ID值如果不存在则读取进程名的hash值
*
* @return 进程ID
* @throws UtilException 进程名称为空
* @throws HutoolException 进程名称为空
* @since 5.7.3
*/
public static int getPid() throws UtilException {
public static int getPid() throws HutoolException {
return Pid.INSTANCE.get();
}

View File

@ -15,7 +15,7 @@ package org.dromara.hutool.core.util;
import org.dromara.hutool.core.bean.BeanUtil;
import org.dromara.hutool.core.collection.CollUtil;
import org.dromara.hutool.core.collection.ListUtil;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.io.file.FileUtil;
import org.dromara.hutool.core.io.IORuntimeException;
import org.dromara.hutool.core.io.IoUtil;
@ -164,10 +164,10 @@ public class XmlUtil {
public static Document readXML(File file) {
Assert.notNull(file, "Xml file is null !");
if (!file.exists()) {
throw new UtilException("File [{}] not a exist!", file.getAbsolutePath());
throw new HutoolException("File [{}] not a exist!", file.getAbsolutePath());
}
if (!file.isFile()) {
throw new UtilException("[{}] not a file!", file.getAbsolutePath());
throw new HutoolException("[{}] not a file!", file.getAbsolutePath());
}
try {
@ -208,10 +208,10 @@ public class XmlUtil {
*
* @param inputStream XML流
* @return XML文档对象
* @throws UtilException IO异常或转换异常
* @throws HutoolException IO异常或转换异常
* @since 3.0.9
*/
public static Document readXML(final InputStream inputStream) throws UtilException {
public static Document readXML(final InputStream inputStream) throws HutoolException {
return readXML(new InputSource(inputStream));
}
@ -220,10 +220,10 @@ public class XmlUtil {
*
* @param reader XML流
* @return XML文档对象
* @throws UtilException IO异常或转换异常
* @throws HutoolException IO异常或转换异常
* @since 3.0.9
*/
public static Document readXML(final Reader reader) throws UtilException {
public static Document readXML(final Reader reader) throws HutoolException {
return readXML(new InputSource(reader));
}
@ -240,7 +240,7 @@ public class XmlUtil {
try {
return builder.parse(source);
} catch (final Exception e) {
throw new UtilException(e, "Parse XML from stream error!");
throw new HutoolException(e, "Parse XML from stream error!");
}
}
@ -327,7 +327,7 @@ public class XmlUtil {
reader.setContentHandler(contentHandler);
reader.parse(source);
} catch (final ParserConfigurationException | SAXException e) {
throw new UtilException(e);
throw new HutoolException(e);
} catch (final IOException e) {
throw new IORuntimeException(e);
}
@ -443,7 +443,7 @@ public class XmlUtil {
try {
write(doc, writer, charset, isPretty ? INDENT_DEFAULT : 0, omitXmlDeclaration);
} catch (final Exception e) {
throw new UtilException(e, "Trans xml document to string error!");
throw new HutoolException(e, "Trans xml document to string error!");
}
return writer.toString();
}
@ -604,7 +604,7 @@ public class XmlUtil {
}
xformer.transform(source, result);
} catch (final Exception e) {
throw new UtilException(e, "Trans xml document to string error!");
throw new HutoolException(e, "Trans xml document to string error!");
}
}
@ -632,7 +632,7 @@ public class XmlUtil {
try {
builder = createDocumentBuilderFactory().newDocumentBuilder();
} catch (final Exception e) {
throw new UtilException(e, "Create xml document error!");
throw new HutoolException(e, "Create xml document error!");
}
return builder;
}
@ -942,7 +942,7 @@ public class XmlUtil {
return xPath.evaluate(expression, source, returnType);
}
} catch (final XPathExpressionException e) {
throw new UtilException(e);
throw new HutoolException(e);
}
}

View File

@ -649,7 +649,7 @@ public class BeanUtilTest {
final Station station2 = new Station();
BeanUtil.copyProperties(station, station2);
Assertions.assertEquals(new Long(123456L), station2.getId());
Assertions.assertEquals(Long.valueOf(123456L), station2.getId());
}
static class Station extends Tree<Long> {}

View File

@ -1,11 +1,11 @@
package org.dromara.hutool.core.collection;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.dromara.hutool.core.date.StopWatch;
import org.dromara.hutool.core.lang.Console;
import org.dromara.hutool.core.lang.page.PageInfo;
import org.dromara.hutool.core.util.RandomUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
@ -262,4 +262,11 @@ public class ListUtilTest {
final List<Integer> reverse = ListUtil.reverseNew(view);
Assertions.assertEquals("[3, 2, 1]", reverse.toString());
}
@Test
void reverseNewTest2() {
final List<Integer> list = ListUtil.of(1, 2, 3);
ListUtil.reverseNew(list);
}
}

View File

@ -1,6 +1,6 @@
package org.dromara.hutool.core.lang;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.thread.ThreadUtil;
import lombok.Data;
import org.junit.jupiter.api.Assertions;
@ -23,7 +23,7 @@ public class SingletonTest {
public TestBean(){
if(null != testSingleton){
throw new UtilException("单例测试中,对象被创建了两次!");
throw new HutoolException("单例测试中,对象被创建了两次!");
}
testSingleton = this;
}

View File

@ -1,7 +1,7 @@
package org.dromara.hutool.core.lang;
import org.dromara.hutool.core.collection.ConcurrentHashSet;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.lang.id.IdUtil;
import org.dromara.hutool.core.lang.id.Snowflake;
import org.dromara.hutool.core.text.StrUtil;
@ -62,7 +62,7 @@ public class SnowflakeTest {
ThreadUtil.concurrencyTest(100, () -> {
for (int i = 0; i < 50000; i++) {
if(!ids.add(snowflake.nextId())){
throw new UtilException("重复ID");
throw new HutoolException("重复ID");
}
}
});
@ -99,7 +99,7 @@ public class SnowflakeTest {
ThreadUtil.concurrencyTest(100, () -> {
for (int i = 0; i < 50000; i++) {
if(!ids.add(snowflake.nextId())){
throw new UtilException("重复ID");
throw new HutoolException("重复ID");
}
}
});

View File

@ -12,6 +12,7 @@ import org.dromara.hutool.core.reflect.lookup.LookupUtil;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledForJreRange;
import java.lang.invoke.*;
import java.lang.reflect.Constructor;
@ -264,19 +265,19 @@ public class LambdaFactoryTest {
@SneakyThrows
private void loop(final int count, final Task... tasks) {
Arrays.stream(tasks)
.peek(task -> {
final LambdaFactoryTest.SupplierThrowable runnable = task.getRunnable();
long cost = System.nanoTime();
for (int i = 0; i < count; i++) {
runnable.get();
}
cost = System.nanoTime() - cost;
task.setCost(cost);
task.setCount(count);
})
.sorted(Comparator.comparing(Task::getCost))
.map(Task::format)
.forEach(System.out::println);
.peek(task -> {
final LambdaFactoryTest.SupplierThrowable runnable = task.getRunnable();
long cost = System.nanoTime();
for (int i = 0; i < count; i++) {
runnable.get();
}
cost = System.nanoTime() - cost;
task.setCost(cost);
task.setCount(count);
})
.sorted(Comparator.comparing(Task::getCost))
.map(Task::format)
.forEach(System.out::println);
System.out.println("--------------------------------------------");
}
@ -318,9 +319,11 @@ public class LambdaFactoryTest {
@SuppressWarnings("unchecked")
@Test
@EnabledForJreRange(max = org.junit.jupiter.api.condition.JRE.JAVA_8)
public void buildStringTest() {
final char[] a = "1234".toCharArray();
// JDK8下无此构造方法
final Constructor<String> constructor = ConstructorUtil.getConstructor(String.class, char[].class, boolean.class);
final BiFunction<char[], Boolean, String> function = LambdaFactory.build(BiFunction.class, constructor);
final String apply = function.apply(a, true);

View File

@ -2,21 +2,35 @@ package org.dromara.hutool.core.map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledForJreRange;
import java.util.concurrent.ConcurrentHashMap;
public class Issue2349Test {
@Test
public void computeIfAbsentTest(){
@EnabledForJreRange(max = org.junit.jupiter.api.condition.JRE.JAVA_8)
public void computeIfAbsentTest() {
// https://blog.csdn.net/xiaochao_bos/article/details/103789991
// 使用ConcurrentHashMap会造成死循环
// SafeConcurrentHashMap用于修复此问题
final ConcurrentHashMap<String,Integer> map=new SafeConcurrentHashMap<>(16);
map.computeIfAbsent("AaAa", key->map.computeIfAbsent("BBBB",key2->42));
final ConcurrentHashMap<String, Integer> map = new SafeConcurrentHashMap<>(16);
map.computeIfAbsent("AaAa", key -> map.computeIfAbsent("BBBB", key2 -> 42));
Assertions.assertEquals(2, map.size());
Assertions.assertEquals(Integer.valueOf(42), map.get("AaAa"));
Assertions.assertEquals(Integer.valueOf(42), map.get("BBBB"));
}
@Test
@EnabledForJreRange(min = org.junit.jupiter.api.condition.JRE.JAVA_9)
public void issue11986ForJava17Test() {
// https://github.com/apache/dubbo/issues/11986
final ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
// JDK9+ has been resolved JDK-8161372 bug, when cause dead then throw IllegalStateException
Assertions.assertThrows(IllegalStateException.class, () -> {
map.computeIfAbsent("AaAa", key -> map.computeIfAbsent("BBBB", key2 -> 42));
});
}
}

View File

@ -272,4 +272,10 @@ public class MapUtilTest {
Assertions.assertEquals(Integer.valueOf(42), map.get("AaAa"));
Assertions.assertEquals(Integer.valueOf(42), map.get("BBBB"));
}
@Test
void createMapTest() {
final Map<Object, Object> map = MapUtil.createMap(MapUtil.view(new HashMap<>()).getClass());
Assertions.assertEquals(HashMap.class, map.getClass());
}
}

View File

@ -1,10 +1,14 @@
package org.dromara.hutool.core.reflect;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.dromara.hutool.core.date.Week;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Map;
public class ConstructorUtilTest {
@ -22,7 +26,7 @@ public class ConstructorUtilTest {
Assertions.assertEquals(0, intValue);
final Integer integer = ConstructorUtil.newInstanceIfPossible(Integer.class);
Assertions.assertEquals(new Integer(0), integer);
Assertions.assertEquals(Integer.valueOf(0), integer);
final Map<?, ?> map = ConstructorUtil.newInstanceIfPossible(Map.class);
Assertions.assertNotNull(map);
@ -36,4 +40,32 @@ public class ConstructorUtilTest {
final int[] intArray = ConstructorUtil.newInstanceIfPossible(int[].class);
Assertions.assertArrayEquals(new int[0], intArray);
}
@Test
void newInstanceTest() {
final TestBean testBean = ConstructorUtil.newInstance(TestBean.class);
Assertions.assertNull(testBean.getA());
Assertions.assertEquals(0, testBean.getB());
}
@Test
void newInstanceAllArgsTest() {
final TestBean testBean = ConstructorUtil.newInstance(TestBean.class, "aValue", 1);
Assertions.assertEquals("aValue", testBean.getA());
Assertions.assertEquals(1, testBean.getB());
}
@Test
void newInstanceHashtableTest() {
final Hashtable<?, ?> testBean = ConstructorUtil.newInstance(Hashtable.class);
Assertions.assertNotNull(testBean);
}
@Data
@NoArgsConstructor
@AllArgsConstructor
private static class TestBean{
private String a;
private int b;
}
}

View File

@ -14,13 +14,13 @@ public class MethodHandleUtilTest {
final Duck duck = (Duck) Proxy.newProxyInstance(
ClassLoaderUtil.getClassLoader(),
new Class[] { Duck.class },
MethodHandleUtil::invokeSpecial);
MethodHandleUtil::invoke);
Assertions.assertEquals("Quack", duck.quack());
// 测试子类执行default方法
final Method quackMethod = MethodUtil.getMethod(Duck.class, "quack");
String quack = MethodHandleUtil.invokeSpecial(new BigDuck(), quackMethod);
String quack = MethodHandleUtil.invoke(new BigDuck(), quackMethod);
Assertions.assertEquals("Quack", quack);
// 测试反射执行默认方法
@ -51,7 +51,7 @@ public class MethodHandleUtilTest {
@Test
public void invokeTest(){
// 测试执行普通方法
final int size = MethodHandleUtil.invokeSpecial(new BigDuck(),
final int size = MethodHandleUtil.invoke(new BigDuck(),
MethodUtil.getMethod(BigDuck.class, "getSize"));
Assertions.assertEquals(36, size);
}

View File

@ -1,12 +1,12 @@
package org.dromara.hutool.core.reflect;
import lombok.Data;
import org.dromara.hutool.core.array.ArrayUtil;
import org.dromara.hutool.core.date.StopWatch;
import org.dromara.hutool.core.lang.Console;
import org.dromara.hutool.core.lang.test.bean.ExamInfoDict;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.util.SystemUtil;
import lombok.Data;
import org.dromara.hutool.core.util.JdkUtil;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
@ -14,7 +14,7 @@ import org.junit.jupiter.api.Test;
import java.lang.reflect.Method;
public class MethodUtilTest {
private static final String JAVA_VERSION = SystemUtil.get("java.version", false);
private static final boolean isGteJdk15 = getJavaVersion() >= 15;
/**
* jdk版本是否>= jdk15
@ -23,10 +23,7 @@ public class MethodUtilTest {
* @author dazer
*/
private static int getJavaVersion() {
if (JAVA_VERSION.startsWith("1.")) {
return Integer.parseInt(JAVA_VERSION.split("\\.")[1]);
}
return Integer.parseInt(JAVA_VERSION.split("\\.")[0]);
return JdkUtil.JVM_VERSION;
}
@Test
@ -244,6 +241,6 @@ public class MethodUtilTest {
final TestClass testClass = new TestClass();
final Method method = MethodUtil.getMethod(TestClass.class, "setA", int.class);
Assertions.assertThrows(IllegalArgumentException.class,
() -> MethodUtil.invoke(testClass, method, "NaN"));
() -> MethodUtil.invoke(testClass, method, "aaa"));
}
}

View File

@ -12,15 +12,24 @@
package org.dromara.hutool.core.reflect.lookup;
import org.dromara.hutool.core.reflect.MethodUtil;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
public class LookupUtilTest {
class LookupUtilTest {
@Test
public void findMethodTest() throws Throwable {
void lookupTest() {
final MethodHandles.Lookup lookup = LookupUtil.lookup();
Assertions.assertNotNull(lookup);
}
@Test
void findMethodTest() throws Throwable {
MethodHandle handle = LookupUtil.findMethod(Duck.class, "quack",
MethodType.methodType(String.class));
Assertions.assertNotNull(handle);
@ -37,7 +46,7 @@ public class LookupUtilTest {
}
@Test
public void findStaticMethodTest() throws Throwable {
void findStaticMethodTest() throws Throwable {
final MethodHandle handle = LookupUtil.findMethod(Duck.class, "getDuck",
MethodType.methodType(String.class, int.class));
Assertions.assertNotNull(handle);
@ -48,7 +57,7 @@ public class LookupUtilTest {
}
@Test
public void findPrivateMethodTest() throws Throwable {
void findPrivateMethodTest() throws Throwable {
final MethodHandle handle = LookupUtil.findMethod(BigDuck.class, "getPrivateValue",
MethodType.methodType(String.class));
Assertions.assertNotNull(handle);
@ -58,7 +67,7 @@ public class LookupUtilTest {
}
@Test
public void findSuperMethodTest() throws Throwable {
void findSuperMethodTest() throws Throwable {
// 查找父类的方法
final MethodHandle handle = LookupUtil.findMethod(BigDuck.class, "quack",
MethodType.methodType(String.class));
@ -69,7 +78,7 @@ public class LookupUtilTest {
}
@Test
public void findPrivateStaticMethodTest() throws Throwable {
void findPrivateStaticMethodTest() throws Throwable {
final MethodHandle handle = LookupUtil.findMethod(BigDuck.class, "getPrivateStaticValue",
MethodType.methodType(String.class));
Assertions.assertNotNull(handle);
@ -78,6 +87,51 @@ public class LookupUtilTest {
Assertions.assertEquals("private static value", invoke);
}
@Test
void unreflectTest() throws Throwable {
final MethodHandle handle = LookupUtil.unreflect(
MethodUtil.getMethodByName(BigDuck.class, "getSize"));
final int invoke = (int) handle.invoke(new BigDuck());
Assertions.assertEquals(36, invoke);
}
@Test
void unreflectPrivateTest() throws Throwable {
final MethodHandle handle = LookupUtil.unreflect(
MethodUtil.getMethodByName(BigDuck.class, "getPrivateValue"));
final String invoke = (String) handle.invoke(new BigDuck());
Assertions.assertEquals("private value", invoke);
}
@Test
void unreflectPrivateStaticTest() throws Throwable {
final MethodHandle handle = LookupUtil.unreflect(
MethodUtil.getMethodByName(BigDuck.class, "getPrivateStaticValue"));
final String invoke = (String) handle.invoke();
Assertions.assertEquals("private static value", invoke);
}
@Test
void unreflectDefaultTest() throws Throwable {
final MethodHandle handle = LookupUtil.unreflect(
MethodUtil.getMethodByName(BigDuck.class, "quack"));
final String invoke = (String) handle.invoke(new BigDuck());
Assertions.assertEquals("Quack", invoke);
}
@Test
void unreflectStaticInInterfaceTest() throws Throwable {
final MethodHandle handle = LookupUtil.unreflect(
MethodUtil.getMethodByName(BigDuck.class, "getDuck"));
final String invoke = (String) handle.invoke(1);
Assertions.assertEquals("Duck 1", invoke);
}
interface Duck {
default String quack() {
return "Quack";

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.spi;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@ -36,7 +36,7 @@ public class ListServiceLoaderTest {
@Test
void getServiceClassNotExistTest() {
final ListServiceLoader<TestSPI1> serviceLoader = ListServiceLoader.of(TestSPI1.class);
Assertions.assertThrows(UtilException.class, ()->{
Assertions.assertThrows(HutoolException.class, ()->{
serviceLoader.getServiceClass(0);
});
}

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.core.spi;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@ -36,7 +36,7 @@ public class MapServiceLoaderTest {
@Test
void getServiceClassNotExistTest() {
final MapServiceLoader<TestSPI1> serviceLoader = MapServiceLoader.of(TestSPI1.class);
Assertions.assertThrows(UtilException.class, ()->{
Assertions.assertThrows(HutoolException.class, ()->{
serviceLoader.getServiceClass("service2");
});
}

View File

@ -5,7 +5,7 @@ import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.dromara.hutool.core.collection.ListUtil;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.map.MapUtil;
import org.dromara.hutool.core.text.placeholder.StrTemplate;
import org.dromara.hutool.core.text.placeholder.template.NamedPlaceholderStrTemplate;
@ -592,7 +592,7 @@ public class StrTemplateTest {
.removeFeatures(StrTemplate.Feature.FORMAT_MISSING_KEY_PRINT_WHOLE_PLACEHOLDER)
.build();
Assertions.assertEquals("this is aaa for 666", template2.format(MapUtil.builder("tableName", "aaa").put("id", "666").build()));
Assertions.assertThrows(UtilException.class, () -> template2.format(MapUtil.builder("tableName", "aaa").build()));
Assertions.assertThrows(HutoolException.class, () -> template2.format(MapUtil.builder("tableName", "aaa").build()));
// ##### 空字符串策略 #####
template = StrTemplate.ofNamed(commonTemplate)

View File

@ -1,6 +1,6 @@
package org.dromara.hutool.core.util;
import org.dromara.hutool.core.exceptions.CloneRuntimeException;
import org.dromara.hutool.core.exceptions.CloneException;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.junit.jupiter.api.Assertions;
@ -46,7 +46,7 @@ public class CloneTest {
try {
return (Cat) super.clone();
} catch (final CloneNotSupportedException e) {
throw new CloneRuntimeException(e);
throw new CloneException(e);
}
}
}
@ -67,7 +67,7 @@ public class CloneTest {
try {
return (Dog) super.clone();
} catch (final CloneNotSupportedException e) {
throw new CloneRuntimeException(e);
throw new CloneException(e);
}
}
}

View File

@ -1,7 +1,7 @@
package org.dromara.hutool.core.util;
import org.dromara.hutool.core.exceptions.CloneRuntimeException;
import org.dromara.hutool.core.exceptions.CloneException;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.junit.jupiter.api.Assertions;
@ -41,7 +41,7 @@ public class DefaultCloneTest {
try {
return (Car) super.clone();
} catch (final CloneNotSupportedException e) {
throw new CloneRuntimeException(e);
throw new CloneException(e);
}
}
}

View File

@ -3,7 +3,7 @@ package org.dromara.hutool.core.util;
import org.dromara.hutool.core.collection.ConcurrentHashSet;
import org.dromara.hutool.core.date.DateUtil;
import org.dromara.hutool.core.date.StopWatch;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.lang.Console;
import org.dromara.hutool.core.lang.id.IdUtil;
import org.dromara.hutool.core.lang.id.Snowflake;
@ -104,7 +104,7 @@ public class IdUtilTest {
try {
latch.await();
} catch (final InterruptedException e) {
throw new UtilException(e);
throw new HutoolException(e);
}
Assertions.assertEquals(threadCount * idCountPerThread, set.size());
}
@ -134,7 +134,7 @@ public class IdUtilTest {
try {
latch.await();
} catch (final InterruptedException e) {
throw new UtilException(e);
throw new HutoolException(e);
}
Assertions.assertEquals(threadCount * idCountPerThread, set.size());
}

View File

@ -438,6 +438,13 @@ public class NumberUtilTest {
}
@Test
public void parseIntOfNaNTest() {
// https://stackoverflow.com/questions/5876369/why-does-casting-double-nan-to-int-not-throw-an-exception-in-java
final int v1 = NumberUtil.parseInt("NaN");
Assertions.assertEquals(0, v1);
}
@Test
public void parseNumberTest() {
// from 5.4.8 issue#I23ORQ@Gitee
@ -488,6 +495,13 @@ public class NumberUtilTest {
Assertions.assertEquals(255, v1);
}
@Test
public void parseNumberOfNaNTest() {
// https://stackoverflow.com/questions/5876369/why-does-casting-double-nan-to-int-not-throw-an-exception-in-java
final Number v1 = NumberUtil.parseNumber("NaN");
Assertions.assertEquals(0, v1.intValue());
}
@Test
public void parseLongTest() {
long number = NumberUtil.parseLong("0xFF");

View File

@ -9,10 +9,7 @@ import org.junit.jupiter.api.Test;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.*;
import java.util.function.Function;
/**
@ -137,7 +134,12 @@ public class ObjUtilTest {
Assertions.assertNotNull(result4);
}
@Test
void cloneListTest() {
final ArrayList<Integer> list = ListUtil.of(1, 2);
final ArrayList<Integer> clone = ObjUtil.clone(list);
Assertions.assertEquals(list, clone);
}
@Test
public void cloneTest() {

View File

@ -13,7 +13,7 @@
package org.dromara.hutool.cron;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.io.resource.NoResourceException;
import org.dromara.hutool.cron.pattern.CronPattern;
import org.dromara.hutool.cron.task.Task;
@ -165,7 +165,7 @@ public class CronUtil {
*/
synchronized public static void start(final boolean isDaemon) {
if (scheduler.isStarted()) {
throw new UtilException("Scheduler has been started, please stop it first!");
throw new HutoolException("Scheduler has been started, please stop it first!");
}
lock.lock();

View File

@ -13,7 +13,7 @@
package org.dromara.hutool.cron.task;
import org.dromara.hutool.core.classloader.ClassLoaderUtil;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.reflect.ConstructorUtil;
import org.dromara.hutool.core.reflect.MethodUtil;
import org.dromara.hutool.core.text.StrUtil;
@ -44,7 +44,7 @@ public class InvokeTask implements Task{
splitIndex = classNameWithMethodName.lastIndexOf('.');
}
if (splitIndex <= 0) {
throw new UtilException("Invalid classNameWithMethodName [{}]!", classNameWithMethodName);
throw new HutoolException("Invalid classNameWithMethodName [{}]!", classNameWithMethodName);
}
//
@ -73,7 +73,7 @@ public class InvokeTask implements Task{
public void execute() {
try {
MethodUtil.invoke(this.obj, this.method);
} catch (final UtilException e) {
} catch (final HutoolException e) {
throw new CronException(e.getCause());
}
}

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.db.ds;
import org.dromara.hutool.core.exceptions.CloneRuntimeException;
import org.dromara.hutool.core.exceptions.CloneException;
import org.dromara.hutool.core.io.IoUtil;
import org.dromara.hutool.core.func.Wrapper;
@ -137,7 +137,7 @@ public class DSWrapper implements Wrapper<DataSource>, DataSource, Closeable, Cl
try {
return (DSWrapper) super.clone();
} catch (final CloneNotSupportedException e) {
throw new CloneRuntimeException(e);
throw new CloneException(e);
}
}
}

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.db.ds.simple;
import org.dromara.hutool.core.exceptions.CloneRuntimeException;
import org.dromara.hutool.core.exceptions.CloneException;
import javax.sql.DataSource;
import java.io.Closeable;
@ -72,7 +72,7 @@ public abstract class AbstractDataSource implements DataSource, Cloneable, Close
try {
return (AbstractDataSource) super.clone();
} catch (final CloneNotSupportedException e) {
throw new CloneRuntimeException(e);
throw new CloneException(e);
}
}
}

View File

@ -13,7 +13,7 @@
package org.dromara.hutool.db.sql;
import org.dromara.hutool.core.convert.Convert;
import org.dromara.hutool.core.exceptions.CloneRuntimeException;
import org.dromara.hutool.core.exceptions.CloneException;
import org.dromara.hutool.core.math.NumberUtil;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.text.split.SplitUtil;
@ -381,7 +381,7 @@ public class Condition implements Cloneable, Serializable {
try {
return (Condition) super.clone();
} catch (final CloneNotSupportedException e) {
throw new CloneRuntimeException(e);
throw new CloneException(e);
}
}

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.extra.spring;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.reflect.TypeReference;
import org.dromara.hutool.core.array.ArrayUtil;
import org.springframework.beans.BeansException;
@ -85,7 +85,7 @@ public class SpringUtil implements BeanFactoryPostProcessor, ApplicationContextA
public static ListableBeanFactory getBeanFactory() {
final ListableBeanFactory factory = null == beanFactory ? applicationContext : beanFactory;
if(null == factory){
throw new UtilException("No ConfigurableListableBeanFactory or ApplicationContext injected, maybe not in the Spring environment?");
throw new HutoolException("No ConfigurableListableBeanFactory or ApplicationContext injected, maybe not in the Spring environment?");
}
return factory;
}
@ -94,17 +94,17 @@ public class SpringUtil implements BeanFactoryPostProcessor, ApplicationContextA
* 获取{@link ConfigurableListableBeanFactory}
*
* @return {@link ConfigurableListableBeanFactory}
* @throws UtilException 当上下文非ConfigurableListableBeanFactory抛出异常
* @throws HutoolException 当上下文非ConfigurableListableBeanFactory抛出异常
* @since 5.7.7
*/
public static ConfigurableListableBeanFactory getConfigurableBeanFactory() throws UtilException {
public static ConfigurableListableBeanFactory getConfigurableBeanFactory() throws HutoolException {
final ConfigurableListableBeanFactory factory;
if (null != beanFactory) {
factory = beanFactory;
} else if (applicationContext instanceof ConfigurableApplicationContext) {
factory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
} else {
throw new UtilException("No ConfigurableListableBeanFactory from context!");
throw new HutoolException("No ConfigurableListableBeanFactory from context!");
}
return factory;
}
@ -268,7 +268,7 @@ public class SpringUtil implements BeanFactoryPostProcessor, ApplicationContextA
final DefaultSingletonBeanRegistry registry = (DefaultSingletonBeanRegistry) factory;
registry.destroySingleton(beanName);
} else {
throw new UtilException("Can not unregister bean, the factory is not a DefaultSingletonBeanRegistry!");
throw new HutoolException("Can not unregister bean, the factory is not a DefaultSingletonBeanRegistry!");
}
}

View File

@ -12,7 +12,7 @@
package org.dromara.hutool.extra.xml;
import org.dromara.hutool.core.exceptions.UtilException;
import org.dromara.hutool.core.exceptions.HutoolException;
import org.dromara.hutool.core.io.file.FileUtil;
import org.dromara.hutool.core.io.IoUtil;
import org.dromara.hutool.core.text.StrUtil;
@ -80,7 +80,7 @@ public class JAXBUtil {
writer = new StringWriter();
marshaller.marshal(bean, writer);
} catch (final Exception e) {
throw new UtilException("convertToXml 错误:" + e.getMessage(), e);
throw new HutoolException("convertToXml 错误:" + e.getMessage(), e);
}
return writer.toString();
}

Some files were not shown because too many files have changed in this diff Show More