Merge remote-tracking branch 'origin/v6-dev' into v6-dev

This commit is contained in:
VampireAchao 2022-06-04 01:18:49 +08:00
commit 03fd58d455
189 changed files with 2395 additions and 2422 deletions

View File

@ -3,7 +3,16 @@
-------------------------------------------------------------------------------------------------------------
# 6.0.0.M1 (2022-04-28)
# 6.0.0.M1 (2022-06-03)
### 计划实现
* 【poi 】 PDF相关
* 【poi 】 HTML、DOCX转换相关
* 【poi 】 Markdown相关如HTML转换等基于commonmark-java
* 【core 】 针对JDK8+的日期统一归档到TimeUtil
* 【core 】 CopyOptions参数重构
* 【db 】 增加DDL封装
* 【json 】 删除JSONNull
### ❌不兼容特性

View File

@ -1,6 +1,6 @@
package cn.hutool.core.annotation;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.SetUtil;
import cn.hutool.core.map.TableMap;
import java.io.Serializable;
@ -42,7 +42,7 @@ public class CombinationAnnotationElement implements AnnotatedElement, Serializa
/**
* 元注解
*/
private static final Set<Class<? extends Annotation>> META_ANNOTATIONS = CollUtil.newHashSet(Target.class, //
private static final Set<Class<? extends Annotation>> META_ANNOTATIONS = SetUtil.of(Target.class, //
Retention.class, //
Inherited.class, //
Documented.class, //

View File

@ -1,6 +1,7 @@
package cn.hutool.core.bean;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.StrUtil;
@ -10,7 +11,6 @@ import cn.hutool.core.util.CharUtil;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -67,7 +67,7 @@ public class BeanPath implements Serializable{
* @param expression 表达式
* @return BeanPath
*/
public static BeanPath create(final String expression) {
public static BeanPath of(final String expression) {
return new BeanPath(expression);
}
@ -80,6 +80,15 @@ public class BeanPath implements Serializable{
init(expression);
}
/**
* 获取表达式解析后的分段列表
*
* @return 表达式分段列表
*/
public List<String> getPatternParts(){
return this.patternParts;
}
/**
* 获取Bean中对应表达式的值
*
@ -107,6 +116,12 @@ public class BeanPath implements Serializable{
set(bean, this.patternParts, value);
}
@Override
public String toString() {
return this.patternParts.toString();
}
//region Private Methods
/**
* 设置表达式指定位置或filed对应的值<br>
* 若表达式指向一个List则设置其坐标对应位置的值若指向Map则put对应key的值Bean则设置字段的值<br>
@ -131,7 +146,6 @@ public class BeanPath implements Serializable{
BeanUtil.setFieldValue(subBean, patternParts.get(patternParts.size() - 1), value);
}
// ------------------------------------------------------------------------------------------------------------------------------------- Private method start
/**
* 获取Bean中对应表达式的值
*
@ -224,6 +238,7 @@ public class BeanPath implements Serializable{
final StringBuilder builder = new StringBuilder();
char c;
boolean isNumStart = false;// 下标标识符开始
boolean isInWrap = false; //标识是否在引号内
for (int i = 0; i < length; i++) {
c = expression.charAt(i);
if (0 == i && '$' == c) {
@ -232,7 +247,13 @@ public class BeanPath implements Serializable{
continue;
}
if (ArrayUtil.contains(EXP_CHARS, c)) {
if('\'' == c){
// 结束
isInWrap = (false == isInWrap);
continue;
}
if (false == isInWrap && ArrayUtil.contains(EXP_CHARS, c)) {
// 处理边界符号
if (CharUtil.BRACKET_END == c) {
// 中括号数字下标结束
@ -252,7 +273,7 @@ public class BeanPath implements Serializable{
// 每一个边界符之前的表达式是一个完整的KEY开始处理KEY
}
if (builder.length() > 0) {
localPatternParts.add(unWrapIfPossible(builder));
localPatternParts.add(builder.toString());
}
builder.setLength(0);
} else {
@ -266,25 +287,12 @@ public class BeanPath implements Serializable{
throw new IllegalArgumentException(StrUtil.format("Bad expression '{}':{}, we find '[' but no ']' !", expression, length - 1));
} else {
if (builder.length() > 0) {
localPatternParts.add(unWrapIfPossible(builder));
localPatternParts.add(builder.toString());
}
}
// 不可变List
this.patternParts = Collections.unmodifiableList(localPatternParts);
this.patternParts = ListUtil.view(localPatternParts);
}
/**
* 对于非表达式去除单引号
*
* @param expression 表达式
* @return 表达式
*/
private static String unWrapIfPossible(final CharSequence expression) {
if (StrUtil.containsAny(expression, " = ", " > ", " < ", " like ", ",")) {
return expression.toString();
}
return StrUtil.unWrap(expression, '\'');
}
// ------------------------------------------------------------------------------------------------------------------------------------- Private method end
//endregion
}

View File

@ -4,6 +4,7 @@ import cn.hutool.core.bean.copier.BeanCopier;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.bean.copier.ValueProvider;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.SetUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.func.Editor;
import cn.hutool.core.map.CaseInsensitiveMap;
@ -340,7 +341,7 @@ public class BeanUtil {
if (null == bean || StrUtil.isBlank(expression)) {
return null;
}
return (T) BeanPath.create(expression).get(bean);
return (T) BeanPath.of(expression).get(bean);
}
/**
@ -353,7 +354,7 @@ public class BeanUtil {
* @since 4.0.6
*/
public static void setProperty(final Object bean, final String expression, final Object value) {
BeanPath.create(expression).set(bean, value);
BeanPath.of(expression).set(bean, value);
}
// --------------------------------------------------------------------------------------------- mapToBean
@ -464,36 +465,6 @@ public class BeanUtil {
return toBean(source, clazz, null);
}
/**
* 对象或Map转Bean忽略字段转换时发生的异常
*
* @param <T> 转换的Bean类型
* @param source Bean对象或Map
* @param clazz 目标的Bean类型
* @return Bean对象
* @since 5.4.0
*/
public static <T> T toBeanIgnoreError(final Object source, final Class<T> clazz) {
return toBean(source, clazz, CopyOptions.create().setIgnoreError(true));
}
/**
* 对象或Map转Bean忽略字段转换时发生的异常
*
* @param <T> 转换的Bean类型
* @param source Bean对象或Map
* @param clazz 目标的Bean类型
* @param ignoreError 是否忽略注入错误
* @return Bean对象
* @since 5.4.0
*/
public static <T> T toBeanIgnoreCase(final Object source, final Class<T> clazz, final boolean ignoreError) {
return toBean(source, clazz,
CopyOptions.create()
.setIgnoreCase(true)
.setIgnoreError(ignoreError));
}
/**
* 对象或Map转Bean
*
@ -512,7 +483,7 @@ public class BeanUtil {
* 对象或Map转Bean
*
* @param <T> 转换的Bean类型
* @param source Bean对象或Map
* @param source Bean对象或Map{@link ValueProvider}
* @param targetSupplier 目标的Bean创建器
* @param options 属性拷贝选项
* @return Bean对象
@ -527,22 +498,6 @@ public class BeanUtil {
return target;
}
/**
* ServletRequest 参数转Bean
*
* @param <T> Bean类型
* @param beanClass Bean Class
* @param valueProvider 值提供者
* @param copyOptions 拷贝选项 {@link CopyOptions}
* @return Bean
*/
public static <T> T toBean(final Class<T> beanClass, final ValueProvider<String> valueProvider, final CopyOptions copyOptions) {
if (null == beanClass || null == valueProvider) {
return null;
}
return fillBean(ConstructorUtil.newInstanceIfPossible(beanClass), valueProvider, copyOptions);
}
/**
* 填充Bean的核心方法
*
@ -559,7 +514,6 @@ public class BeanUtil {
return BeanCopier.create(valueProvider, bean, copyOptions).copy();
}
// --------------------------------------------------------------------------------------------- beanToMap
/**
@ -572,14 +526,16 @@ public class BeanUtil {
* @since 5.8.0
*/
public static Map<String, Object> beanToMap(final Object bean, final String... properties) {
int mapSize = 16;
Editor<String> keyEditor = null;
if(ArrayUtil.isNotEmpty(properties)){
final Set<String> propertiesSet = CollUtil.set(false, properties);
if (ArrayUtil.isNotEmpty(properties)) {
mapSize = properties.length;
final Set<String> propertiesSet = SetUtil.of(properties);
keyEditor = property -> propertiesSet.contains(property) ? property : null;
}
// 指明了要复制的属性 所以不忽略null值
return beanToMap(bean, new LinkedHashMap<>(properties.length, 1), false, keyEditor);
return beanToMap(bean, new LinkedHashMap<>(mapSize, 1), false, keyEditor);
}
/**
@ -682,6 +638,9 @@ public class BeanUtil {
* @return 目标对象
*/
public static <T> T copyProperties(final Object source, final Class<T> tClass, final String... ignoreProperties) {
if (null == source) {
return null;
}
final T target = ConstructorUtil.newInstanceIfPossible(tClass);
copyProperties(source, target, CopyOptions.create().setIgnoreProperties(ignoreProperties));
return target;
@ -719,6 +678,9 @@ public class BeanUtil {
* @param copyOptions 拷贝选项 {@link CopyOptions}
*/
public static void copyProperties(final Object source, final Object target, final CopyOptions copyOptions) {
if (null == source || null == target) {
return;
}
BeanCopier.create(source, target, ObjUtil.defaultIfNull(copyOptions, CopyOptions::create)).copy();
}

View File

@ -1,5 +1,6 @@
package cn.hutool.core.bean.copier;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.copier.Copier;
import java.io.Serializable;
@ -16,9 +17,8 @@ import java.util.Map;
* 4. Map Map
* </pre>
*
* @author looly
*
* @param <T> 目标对象类型
* @author looly
* @since 3.2.3
*/
public class BeanCopier<T> implements Copier<T>, Serializable {
@ -29,9 +29,9 @@ public class BeanCopier<T> implements Copier<T>, Serializable {
/**
* 创建BeanCopier
*
* @param <T> 目标Bean类型
* @param source 来源对象可以是Bean或者Map
* @param target 目标Bean对象
* @param <T> 目标Bean类型
* @param source 来源对象可以是Bean或者Map
* @param target 目标Bean对象
* @param copyOptions 拷贝属性选项
* @return BeanCopier
*/
@ -42,10 +42,10 @@ public class BeanCopier<T> implements Copier<T>, Serializable {
/**
* 创建BeanCopier
*
* @param <T> 目标Bean类型
* @param source 来源对象可以是Bean或者Map
* @param target 目标Bean对象
* @param destType 目标的泛型类型用于标注有泛型参数的Bean对象
* @param <T> 目标Bean类型
* @param source 来源对象可以是Bean或者Map
* @param target 目标Bean对象
* @param destType 目标的泛型类型用于标注有泛型参数的Bean对象
* @param copyOptions 拷贝属性选项
* @return BeanCopier
*/
@ -56,13 +56,15 @@ public class BeanCopier<T> implements Copier<T>, Serializable {
/**
* 构造
*
* @param source 来源对象可以是Bean或者Map
* @param target 目标Bean对象
* @param targetType 目标的泛型类型用于标注有泛型参数的Bean对象
* @param source 来源对象可以是Bean或者Map不能为{@code null}
* @param target 目标Bean对象不能为{@code null}
* @param targetType 目标的泛型类型用于标注有泛型参数的Bean对象
* @param copyOptions 拷贝属性选项
*/
@SuppressWarnings("unchecked")
public BeanCopier(final Object source, final T target, final Type targetType, final CopyOptions copyOptions) {
Assert.notNull(source, "Source bean must be not null!");
Assert.notNull(target, "Target bean must be not null!");
final Copier<T> copier;
if (source instanceof Map) {
if (target instanceof Map) {
@ -70,7 +72,7 @@ public class BeanCopier<T> implements Copier<T>, Serializable {
} else {
copier = new MapToBeanCopier<>((Map<?, ?>) source, target, targetType, copyOptions);
}
}else if(source instanceof ValueProvider){
} else if (source instanceof ValueProvider) {
//noinspection unchecked
copier = new ValueProviderToBeanCopier<>((ValueProvider<String>) source, target, targetType, copyOptions);
} else {

View File

@ -24,7 +24,7 @@ public class MapToMapCopier extends AbsCopier<Map, Map> {
* @param source 来源Map
* @param target 目标Bean对象
* @param targetType 目标泛型类型
* @param copyOptions 拷贝选项
* @param copyOptions 拷贝选项{@code null}使用默认配置
*/
public MapToMapCopier(final Map source, final Map target, final Type targetType, final CopyOptions copyOptions) {
super(source, target, copyOptions);

View File

@ -3,7 +3,7 @@ package cn.hutool.core.classloader;
import cn.hutool.core.convert.BasicType;
import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.map.WeakConcurrentMap;
import cn.hutool.core.text.CharPool;
import cn.hutool.core.text.StrUtil;
@ -50,7 +50,7 @@ public class ClassLoaderUtil {
* 原始类型名和其class对应表例如int = int.class
*/
private static final Map<String, Class<?>> PRIMITIVE_TYPE_NAME_MAP = new ConcurrentHashMap<>(32);
private static final WeakConcurrentMap<Pair<String, ClassLoader>, Class<?>> CLASS_CACHE = new WeakConcurrentMap<>();
private static final WeakConcurrentMap<Map.Entry<String, ClassLoader>, Class<?>> CLASS_CACHE = new WeakConcurrentMap<>();
static {
final List<Class<?>> primitiveTypes = new ArrayList<>(32);
@ -202,7 +202,7 @@ public class ClassLoaderUtil {
if (clazz == null) {
final String finalName = name;
final ClassLoader finalClassLoader = classLoader;
clazz = CLASS_CACHE.computeIfAbsent(Pair.of(name, classLoader), (key)-> doLoadClass(finalName, finalClassLoader, isInitialized));
clazz = CLASS_CACHE.computeIfAbsent(MapUtil.entry(name, classLoader), (key)-> doLoadClass(finalName, finalClassLoader, isInitialized));
}
return (Class<T>) clazz;
}

View File

@ -55,7 +55,6 @@ import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.function.BiConsumer;
import java.util.function.Function;
@ -122,7 +121,7 @@ public class CollUtil {
final ArrayList<T> list = new ArrayList<>(Math.max(coll1.size(), coll2.size()));
final Map<T, Integer> map1 = countMap(coll1);
final Map<T, Integer> map2 = countMap(coll2);
final Set<T> elts = newHashSet(coll2);
final Set<T> elts = SetUtil.of(coll2);
elts.addAll(coll1);
int m;
for (final T t : elts) {
@ -239,7 +238,7 @@ public class CollUtil {
final ArrayList<T> list = new ArrayList<>(Math.min(coll1.size(), coll2.size()));
final Map<T, Integer> map1 = countMap(coll1);
final Map<T, Integer> map2 = countMap(coll2);
final Set<T> elts = newHashSet(coll2);
final Set<T> elts = SetUtil.of(coll2);
int m;
for (final T t : elts) {
m = Math.min(Convert.toInt(map1.get(t), 0), Convert.toInt(map2.get(t), 0));
@ -348,7 +347,7 @@ public class CollUtil {
final List<T> result = new ArrayList<>();
final Map<T, Integer> map1 = countMap(coll1);
final Map<T, Integer> map2 = countMap(coll2);
final Set<T> elts = newHashSet(coll2);
final Set<T> elts = SetUtil.of(coll2);
elts.addAll(coll1);
int m;
for (final T t : elts) {
@ -401,7 +400,7 @@ public class CollUtil {
return ListUtil.empty();
}
if (isEmpty(coll2)) {
return ListUtil.list(true, coll1);
return ListUtil.of(true, coll1);
}
//将被交数用链表储存防止因为频繁扩容影响性能
@ -654,300 +653,6 @@ public class CollUtil {
return currentAlaDatas;
}
// ----------------------------------------------------------------------------------------------- new HashSet
/**
* 新建一个HashSet
*
* @param <T> 集合元素类型
* @param ts 元素数组
* @return HashSet对象
*/
@SafeVarargs
public static <T> HashSet<T> newHashSet(final T... ts) {
return set(false, ts);
}
/**
* 新建一个LinkedHashSet
*
* @param <T> 集合元素类型
* @param ts 元素数组
* @return HashSet对象
* @since 4.1.10
*/
@SafeVarargs
public static <T> LinkedHashSet<T> newLinkedHashSet(final T... ts) {
return (LinkedHashSet<T>) set(true, ts);
}
/**
* 新建一个HashSet
*
* @param <T> 集合元素类型
* @param isSorted 是否有序有序返回 {@link LinkedHashSet}否则返回 {@link HashSet}
* @param ts 元素数组
* @return HashSet对象
*/
@SafeVarargs
public static <T> HashSet<T> set(final boolean isSorted, final T... ts) {
if (null == ts) {
return isSorted ? new LinkedHashSet<>() : new HashSet<>();
}
final int initialCapacity = Math.max((int) (ts.length / .75f) + 1, 16);
final HashSet<T> set = isSorted ? new LinkedHashSet<>(initialCapacity) : new HashSet<>(initialCapacity);
Collections.addAll(set, ts);
return set;
}
/**
* 新建一个HashSet
*
* @param <T> 集合元素类型
* @param collection 集合
* @return HashSet对象
*/
public static <T> HashSet<T> newHashSet(final Collection<T> collection) {
return newHashSet(false, collection);
}
/**
* 新建一个HashSet
*
* @param <T> 集合元素类型
* @param isSorted 是否有序有序返回 {@link LinkedHashSet}否则返回{@link HashSet}
* @param collection 集合用于初始化Set
* @return HashSet对象
*/
public static <T> HashSet<T> newHashSet(final boolean isSorted, final Collection<T> collection) {
return isSorted ? new LinkedHashSet<>(collection) : new HashSet<>(collection);
}
/**
* 新建一个HashSet
*
* @param <T> 集合元素类型
* @param isSorted 是否有序有序返回 {@link LinkedHashSet}否则返回{@link HashSet}
* @param iter {@link Iterator}
* @return HashSet对象
* @since 3.0.8
*/
public static <T> HashSet<T> newHashSet(final boolean isSorted, final Iterator<T> iter) {
if (null == iter) {
return set(isSorted, (T[]) null);
}
final HashSet<T> set = isSorted ? new LinkedHashSet<>() : new HashSet<>();
while (iter.hasNext()) {
set.add(iter.next());
}
return set;
}
/**
* 新建一个HashSet
*
* @param <T> 集合元素类型
* @param isSorted 是否有序有序返回 {@link LinkedHashSet}否则返回{@link HashSet}
* @param enumeration {@link Enumeration}
* @return HashSet对象
* @since 3.0.8
*/
public static <T> HashSet<T> newHashSet(final boolean isSorted, final Enumeration<T> enumeration) {
if (null == enumeration) {
return set(isSorted, (T[]) null);
}
final HashSet<T> set = isSorted ? new LinkedHashSet<>() : new HashSet<>();
while (enumeration.hasMoreElements()) {
set.add(enumeration.nextElement());
}
return set;
}
// ----------------------------------------------------------------------------------------------- List
/**
* 新建一个空List
*
* @param <T> 集合元素类型
* @param isLinked 是否新建LinkedList
* @return List对象
* @since 4.1.2
*/
public static <T> List<T> list(final boolean isLinked) {
return ListUtil.list(isLinked);
}
/**
* 新建一个List
*
* @param <T> 集合元素类型
* @param isLinked 是否新建LinkedList
* @param values 数组
* @return List对象
* @since 4.1.2
*/
@SafeVarargs
public static <T> List<T> list(final boolean isLinked, final T... values) {
return ListUtil.list(isLinked, values);
}
/**
* 新建一个List
*
* @param <T> 集合元素类型
* @param isLinked 是否新建LinkedList
* @param collection 集合
* @return List对象
* @since 4.1.2
*/
public static <T> List<T> list(final boolean isLinked, final Collection<T> collection) {
return ListUtil.list(isLinked, collection);
}
/**
* 新建一个List<br>
* 提供的参数为null时返回空{@link ArrayList}
*
* @param <T> 集合元素类型
* @param isLinked 是否新建LinkedList
* @param iterable {@link Iterable}
* @return List对象
* @since 4.1.2
*/
public static <T> List<T> list(final boolean isLinked, final Iterable<T> iterable) {
return ListUtil.list(isLinked, iterable);
}
/**
* 新建一个ArrayList<br>
* 提供的参数为null时返回空{@link ArrayList}
*
* @param <T> 集合元素类型
* @param isLinked 是否新建LinkedList
* @param iter {@link Iterator}
* @return ArrayList对象
* @since 4.1.2
*/
public static <T> List<T> list(final boolean isLinked, final Iterator<T> iter) {
return ListUtil.list(isLinked, iter);
}
/**
* 新建一个List<br>
* 提供的参数为null时返回空{@link ArrayList}
*
* @param <T> 集合元素类型
* @param isLinked 是否新建LinkedList
* @param enumeration {@link Enumeration}
* @return ArrayList对象
* @since 3.0.8
*/
public static <T> List<T> list(final boolean isLinked, final Enumeration<T> enumeration) {
return ListUtil.list(isLinked, enumeration);
}
/**
* 新建一个ArrayList
*
* @param <T> 集合元素类型
* @param values 数组
* @return ArrayList对象
* @see #toList(Object[])
*/
@SafeVarargs
public static <T> ArrayList<T> newArrayList(final T... values) {
return ListUtil.toList(values);
}
/**
* 数组转为ArrayList
*
* @param <T> 集合元素类型
* @param values 数组
* @return ArrayList对象
* @since 4.0.11
*/
@SafeVarargs
public static <T> ArrayList<T> toList(final T... values) {
return ListUtil.toList(values);
}
/**
* 新建一个ArrayList
*
* @param <T> 集合元素类型
* @param collection 集合
* @return ArrayList对象
*/
public static <T> ArrayList<T> newArrayList(final Collection<T> collection) {
return ListUtil.toList(collection);
}
/**
* 新建一个ArrayList<br>
* 提供的参数为null时返回空{@link ArrayList}
*
* @param <T> 集合元素类型
* @param iterable {@link Iterable}
* @return ArrayList对象
* @since 3.1.0
*/
public static <T> ArrayList<T> newArrayList(final Iterable<T> iterable) {
return ListUtil.toList(iterable);
}
/**
* 新建一个ArrayList<br>
* 提供的参数为null时返回空{@link ArrayList}
*
* @param <T> 集合元素类型
* @param iterator {@link Iterator}
* @return ArrayList对象
* @since 3.0.8
*/
public static <T> ArrayList<T> newArrayList(final Iterator<T> iterator) {
return ListUtil.toList(iterator);
}
/**
* 新建一个ArrayList<br>
* 提供的参数为null时返回空{@link ArrayList}
*
* @param <T> 集合元素类型
* @param enumeration {@link Enumeration}
* @return ArrayList对象
* @since 3.0.8
*/
public static <T> ArrayList<T> newArrayList(final Enumeration<T> enumeration) {
return ListUtil.toList(enumeration);
}
// ----------------------------------------------------------------------new LinkedList
/**
* 新建LinkedList
*
* @param values 数组
* @param <T> 类型
* @return LinkedList
* @since 4.1.2
*/
@SafeVarargs
public static <T> LinkedList<T> newLinkedList(final T... values) {
return ListUtil.toLinkedList(values);
}
/**
* 新建一个CopyOnWriteArrayList
*
* @param <T> 集合元素类型
* @param collection 集合
* @return {@link CopyOnWriteArrayList}
*/
public static <T> CopyOnWriteArrayList<T> newCopyOnWriteArrayList(final Collection<T> collection) {
return ListUtil.toCopyOnWriteArrayList(collection);
}
/**
* 新建{@link BlockingQueue}<br>
* 在队列为空时获取元素的线程会等待队列变为非空当队列满时存储元素的线程会等待队列可用
@ -1125,7 +830,7 @@ public class CollUtil {
return ListUtil.empty();
}
final List<T> list = collection instanceof List ? (List<T>) collection : ListUtil.toList(collection);
final List<T> list = collection instanceof List ? (List<T>) collection : ListUtil.of(collection);
return sub(list, start, end, step);
}
@ -1222,7 +927,7 @@ public class CollUtil {
*/
@SuppressWarnings("unchecked")
public static <T extends Collection<E>, E> T removeAny(final T collection, final E... elesRemoved) {
collection.removeAll(newHashSet(elesRemoved));
collection.removeAll(SetUtil.of(elesRemoved));
return collection;
}
@ -1236,7 +941,7 @@ public class CollUtil {
* @return 处理后的集合
* @since 4.6.5
*/
public static <T extends Collection<E>, E> T filter(final T collection, final Filter<E> filter) {
public static <T extends Collection<E>, E> T filter(final T collection, final Predicate<E> filter) {
return IterUtil.filter(collection, filter);
}
@ -1927,7 +1632,7 @@ public class CollUtil {
* @since 3.0.9
*/
public static <E> Collection<E> toCollection(final Iterable<E> iterable) {
return (iterable instanceof Collection) ? (Collection<E>) iterable : newArrayList(iterable.iterator());
return (iterable instanceof Collection) ? (Collection<E>) iterable : ListUtil.of(iterable.iterator());
}
/**
@ -2082,7 +1787,7 @@ public class CollUtil {
iter = StrUtil.splitTrim(ArrayStr, CharUtil.COMMA).iterator();
} else {
// 其它类型按照单一元素处理
iter = CollUtil.newArrayList(value).iterator();
iter = ListUtil.of(value).iterator();
}
final ConverterRegistry convert = ConverterRegistry.getInstance();
@ -2522,14 +2227,14 @@ public class CollUtil {
// ------------------------------------------------------------------------------------------------- forEach
/**
* 循环遍历 {@link Iterable}使用{@link Consumer} 接受遍历的每条数据并针对每条数据做处理
* 循环遍历 {@link Iterable}使用{@link IndexedConsumer} 接受遍历的每条数据并针对每条数据做处理
*
* @param <T> 集合元素类型
* @param iterable {@link Iterable}
* @param consumer {@link Consumer} 遍历的每条数据处理器
* @param consumer {@link IndexedConsumer} 遍历的每条数据处理器
* @since 5.4.7
*/
public static <T> void forEach(final Iterable<T> iterable, final Consumer<T> consumer) {
public static <T> void forEach(final Iterable<T> iterable, final IndexedConsumer<T> consumer) {
if (iterable == null) {
return;
}
@ -2537,13 +2242,13 @@ public class CollUtil {
}
/**
* 循环遍历 {@link Iterator}使用{@link Consumer} 接受遍历的每条数据并针对每条数据做处理
* 循环遍历 {@link Iterator}使用{@link IndexedConsumer} 接受遍历的每条数据并针对每条数据做处理
*
* @param <T> 集合元素类型
* @param iterator {@link Iterator}
* @param consumer {@link Consumer} 遍历的每条数据处理器
* @param consumer {@link IndexedConsumer} 遍历的每条数据处理器
*/
public static <T> void forEach(final Iterator<T> iterator, final Consumer<T> consumer) {
public static <T> void forEach(final Iterator<T> iterator, final IndexedConsumer<T> consumer) {
if (iterator == null) {
return;
}
@ -2555,13 +2260,13 @@ public class CollUtil {
}
/**
* 循环遍历 {@link Enumeration}使用{@link Consumer} 接受遍历的每条数据并针对每条数据做处理
* 循环遍历 {@link Enumeration}使用{@link IndexedConsumer} 接受遍历的每条数据并针对每条数据做处理
*
* @param <T> 集合元素类型
* @param enumeration {@link Enumeration}
* @param consumer {@link Consumer} 遍历的每条数据处理器
* @param consumer {@link IndexedConsumer} 遍历的每条数据处理器
*/
public static <T> void forEach(final Enumeration<T> enumeration, final Consumer<T> consumer) {
public static <T> void forEach(final Enumeration<T> enumeration, final IndexedConsumer<T> consumer) {
if (enumeration == null) {
return;
}
@ -2573,15 +2278,15 @@ public class CollUtil {
}
/**
* 循环遍历Map使用{@link KVConsumer} 接受遍历的每条数据并针对每条数据做处理<br>
* 循环遍历Map使用{@link IndexedKVConsumer} 接受遍历的每条数据并针对每条数据做处理<br>
* 和JDK8中的map.forEach不同的是此方法支持index
*
* @param <K> Key类型
* @param <V> Value类型
* @param map {@link Map}
* @param kvConsumer {@link KVConsumer} 遍历的每条数据处理器
* @param kvConsumer {@link IndexedKVConsumer} 遍历的每条数据处理器
*/
public static <K, V> void forEach(final Map<K, V> map, final KVConsumer<K, V> kvConsumer) {
public static <K, V> void forEach(final Map<K, V> map, final IndexedKVConsumer<K, V> kvConsumer) {
if (map == null) {
return;
}
@ -2618,11 +2323,11 @@ public class CollUtil {
while (result.size() - 1 < index) {
result.add(null);
}
result.set(index, newArrayList(t));
result.set(index, ListUtil.of(t));
} else {
subList = result.get(index);
if (null == subList) {
result.set(index, newArrayList(t));
result.set(index, ListUtil.of(t));
} else {
subList.add(t);
}
@ -2661,30 +2366,6 @@ public class CollUtil {
});
}
/**
* 反序给定List会在原List基础上直接修改
*
* @param <T> 元素类型
* @param list 被反转的List
* @return 反转后的List
* @since 4.0.6
*/
public static <T> List<T> reverse(final List<T> list) {
return ListUtil.reverse(list);
}
/**
* 反序给定List会创建一个新的List原List数据不变
*
* @param <T> 元素类型
* @param list 被反转的List
* @return 反转后的List
* @since 4.0.6
*/
public static <T> List<T> reverseNew(final List<T> list) {
return ListUtil.reverseNew(list);
}
/**
* 设置或增加元素当index小于List的长度时替换指定位置的值否则在尾部追加
*
@ -2903,7 +2584,7 @@ public class CollUtil {
* @author Looly
*/
@FunctionalInterface
public interface Consumer<T> extends Serializable {
public interface IndexedConsumer<T> extends Serializable {
/**
* 接受并处理一个参数
*
@ -2921,7 +2602,7 @@ public class CollUtil {
* @author Looly
*/
@FunctionalInterface
public interface KVConsumer<K, V> extends Serializable {
public interface IndexedKVConsumer<K, V> extends Serializable {
/**
* 接受并处理一对参数
*

View File

@ -1,8 +1,6 @@
package cn.hutool.core.collection;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
/**
@ -13,20 +11,16 @@ import java.util.concurrent.ConcurrentHashMap;
* @param <E> 元素类型
* @since 3.1.0
*/
public class ConcurrentHashSet<E> extends AbstractSet<E> implements java.io.Serializable {
public class ConcurrentHashSet<E> extends SetFromMap<E> {
private static final long serialVersionUID = 7997886765361607470L;
/** 持有对象。如果值为此对象表示有数据,否则无数据 */
private static final Boolean PRESENT = true;
private final ConcurrentHashMap<E, Boolean> map;
// ----------------------------------------------------------------------------------- Constructor start
/**
* 构造<br>
* 触发因子为默认的0.75
*/
public ConcurrentHashSet() {
map = new ConcurrentHashMap<>();
super(new ConcurrentHashMap<>());
}
/**
@ -36,7 +30,7 @@ public class ConcurrentHashSet<E> extends AbstractSet<E> implements java.io.Seri
* @param initialCapacity 初始大小
*/
public ConcurrentHashSet(final int initialCapacity) {
map = new ConcurrentHashMap<>(initialCapacity);
super(new ConcurrentHashMap<>(initialCapacity));
}
/**
@ -46,7 +40,7 @@ public class ConcurrentHashSet<E> extends AbstractSet<E> implements java.io.Seri
* @param loadFactor 加载因子此参数决定数据增长时触发的百分比
*/
public ConcurrentHashSet(final int initialCapacity, final float loadFactor) {
map = new ConcurrentHashMap<>(initialCapacity, loadFactor);
super(new ConcurrentHashMap<>(initialCapacity, loadFactor));
}
/**
@ -57,7 +51,7 @@ public class ConcurrentHashSet<E> extends AbstractSet<E> implements java.io.Seri
* @param concurrencyLevel 线程并发度
*/
public ConcurrentHashSet(final int initialCapacity, final float loadFactor, final int concurrencyLevel) {
map = new ConcurrentHashMap<>(initialCapacity, loadFactor, concurrencyLevel);
super(new ConcurrentHashMap<>(initialCapacity, loadFactor, concurrencyLevel));
}
/**
@ -65,52 +59,14 @@ public class ConcurrentHashSet<E> extends AbstractSet<E> implements java.io.Seri
* @param iter {@link Iterable}
*/
public ConcurrentHashSet(final Iterable<E> iter) {
super(iter instanceof Collection ? new ConcurrentHashMap<>((int)(((Collection<E>)iter).size() / 0.75f)) : new ConcurrentHashMap<>());
if(iter instanceof Collection) {
final Collection<E> collection = (Collection<E>)iter;
map = new ConcurrentHashMap<>((int)(collection.size() / 0.75f));
this.addAll(collection);
this.addAll((Collection<E>)iter);
}else {
map = new ConcurrentHashMap<>();
for (final E e : iter) {
this.add(e);
}
}
}
// ----------------------------------------------------------------------------------- Constructor end
@Override
public Iterator<E> iterator() {
return map.keySet().iterator();
}
@Override
public int size() {
return map.size();
}
@Override
public boolean isEmpty() {
return map.isEmpty();
}
@Override
public boolean contains(final Object o) {
//noinspection SuspiciousMethodCalls
return map.containsKey(o);
}
@Override
public boolean add(final E e) {
return map.put(e, PRESENT) == null;
}
@Override
public boolean remove(final Object o) {
return PRESENT.equals(map.remove(o));
}
@Override
public void clear() {
map.clear();
}
}

View File

@ -1,5 +1,6 @@
package cn.hutool.core.collection;
import cn.hutool.core.collection.iter.EnumerationIter;
import cn.hutool.core.collection.partition.AvgPartition;
import cn.hutool.core.collection.partition.Partition;
import cn.hutool.core.collection.partition.RandomAccessAvgPartition;
@ -29,51 +30,53 @@ import java.util.function.Consumer;
* @author looly
*/
public class ListUtil {
/**
* 新建一个空List
*
* @param <T> 集合元素类型
* @param isLinked 是否新建LinkedList
* @return List对象
* @since 4.1.2
*/
public static <T> List<T> list(final boolean isLinked) {
return isLinked ? new LinkedList<>() : new ArrayList<>();
}
/**
* 新建一个List
* 新建一个List<br>
* 如果提供的初始化数组为空新建默认初始长度的List
*
* @param <T> 集合元素类型
* @param isLinked 是否新建LinkedList
* @param values 数组
* @param <T> 集合元素类型
* @param values 数组可以为{@code null}
* @return List对象
* @since 4.1.2
*/
@SafeVarargs
public static <T> List<T> list(final boolean isLinked, final T... values) {
public static <T> ArrayList<T> of(final T... values) {
if (ArrayUtil.isEmpty(values)) {
return list(isLinked);
return new ArrayList<>();
}
final List<T> arrayList = isLinked ? new LinkedList<>() : new ArrayList<>(values.length);
final ArrayList<T> arrayList = new ArrayList<>(values.length);
Collections.addAll(arrayList, values);
return arrayList;
}
/**
* 新建一个List
* 新建一个{@link LinkedList}<br>
* 如果提供的初始化数组为空新建默认初始长度的List
*
* @param <T> 集合元素类型
* @param isLinked 是否新建LinkedList
* @param collection 集合
* @return List对象
* @since 4.1.2
* @param <T> 集合元素类型
* @param values 数组可以为{@code null}
* @return {@link LinkedList}对象
*/
public static <T> List<T> list(final boolean isLinked, final Collection<T> collection) {
if (null == collection) {
return list(isLinked);
@SafeVarargs
public static <T> LinkedList<T> ofLinked(final T... values) {
final LinkedList<T> list = new LinkedList<>();
if (ArrayUtil.isNotEmpty(values)) {
Collections.addAll(list, values);
}
return isLinked ? new LinkedList<>(collection) : new ArrayList<>(collection);
return list;
}
/**
* 新建一个List<br>
* 如果提供的初始化数组为空新建默认初始长度的List
*
* @param <T> 集合元素类型
* @param isLinked 是否为链表
* @return List对象
*/
public static <T> List<T> of(final boolean isLinked) {
return isLinked ? ofLinked() : of();
}
/**
@ -86,31 +89,15 @@ public class ListUtil {
* @return List对象
* @since 4.1.2
*/
public static <T> List<T> list(final boolean isLinked, final Iterable<T> iterable) {
public static <T> List<T> of(final boolean isLinked, final Iterable<T> iterable) {
if (null == iterable) {
return list(isLinked);
return of(isLinked);
}
return list(isLinked, iterable.iterator());
}
/**
* 新建一个List<br>
* 提供的参数为null时返回空{@link ArrayList}
*
* @param <T> 集合元素类型
* @param isLinked 是否新建LinkedList
* @param iter {@link Iterator}
* @return ArrayList对象
* @since 4.1.2
*/
public static <T> List<T> list(final boolean isLinked, final Iterator<T> iter) {
final List<T> list = list(isLinked);
if (null != iter) {
while (iter.hasNext()) {
list.add(iter.next());
}
if (iterable instanceof Collection) {
final Collection<T> collection = (Collection<T>) iterable;
return isLinked ? new LinkedList<>(collection) : new ArrayList<>(collection);
}
return list;
return of(isLinked, iterable.iterator());
}
/**
@ -123,80 +110,30 @@ public class ListUtil {
* @return ArrayList对象
* @since 3.0.8
*/
public static <T> List<T> list(final boolean isLinked, final Enumeration<T> enumration) {
final List<T> list = list(isLinked);
if (null != enumration) {
while (enumration.hasMoreElements()) {
list.add(enumration.nextElement());
public static <T> List<T> of(final boolean isLinked, final Enumeration<T> enumration) {
return of(isLinked, (Iterator<T>) new EnumerationIter<>(enumration));
}
/**
* 新建一个List<br>
* 提供的参数为null时返回空{@link ArrayList}
*
* @param <T> 集合元素类型
* @param isLinked 是否新建LinkedList
* @param iter {@link Iterator}
* @return ArrayList对象
* @since 4.1.2
*/
public static <T> List<T> of(final boolean isLinked, final Iterator<T> iter) {
final List<T> list = of(isLinked);
if (null != iter) {
while (iter.hasNext()) {
list.add(iter.next());
}
}
return list;
}
/**
* 新建一个ArrayList
*
* @param <T> 集合元素类型
* @param values 数组
* @return ArrayList对象
*/
@SafeVarargs
public static <T> ArrayList<T> toList(final T... values) {
return (ArrayList<T>) list(false, values);
}
/**
* 新建LinkedList
*
* @param values 数组
* @param <T> 类型
* @return LinkedList
* @since 4.1.2
*/
@SafeVarargs
public static <T> LinkedList<T> toLinkedList(final T... values) {
return (LinkedList<T>) list(true, values);
}
/**
* 数组转为一个不可变List<br>
* 类似于Java9中的List.of
*
* @param ts 对象
* @param <T> 对象类型
* @return 不可修改List
* @since 5.4.3
*/
@SafeVarargs
public static <T> List<T> of(final T... ts) {
if (ArrayUtil.isEmpty(ts)) {
return Collections.emptyList();
}
return Collections.unmodifiableList(toList(ts));
}
/**
* 新建一个CopyOnWriteArrayList
*
* @param <T> 集合元素类型
* @param collection 集合
* @return {@link CopyOnWriteArrayList}
*/
public static <T> CopyOnWriteArrayList<T> toCopyOnWriteArrayList(final Collection<T> collection) {
return (null == collection) ? (new CopyOnWriteArrayList<>()) : (new CopyOnWriteArrayList<>(collection));
}
/**
* 新建一个ArrayList
*
* @param <T> 集合元素类型
* @param collection 集合
* @return ArrayList对象
*/
public static <T> ArrayList<T> toList(final Collection<T> collection) {
return (ArrayList<T>) list(false, collection);
}
/**
* 新建一个ArrayList<br>
* 提供的参数为null时返回空{@link ArrayList}
@ -206,8 +143,8 @@ public class ListUtil {
* @return ArrayList对象
* @since 3.1.0
*/
public static <T> ArrayList<T> toList(final Iterable<T> iterable) {
return (ArrayList<T>) list(false, iterable);
public static <T> ArrayList<T> of(final Iterable<T> iterable) {
return (ArrayList<T>) of(false, iterable);
}
/**
@ -219,8 +156,8 @@ public class ListUtil {
* @return ArrayList对象
* @since 3.0.8
*/
public static <T> ArrayList<T> toList(final Iterator<T> iterator) {
return (ArrayList<T>) list(false, iterator);
public static <T> ArrayList<T> of(final Iterator<T> iterator) {
return (ArrayList<T>) of(false, iterator);
}
/**
@ -232,8 +169,71 @@ public class ListUtil {
* @return ArrayList对象
* @since 3.0.8
*/
public static <T> ArrayList<T> toList(final Enumeration<T> enumeration) {
return (ArrayList<T>) list(false, enumeration);
public static <T> ArrayList<T> of(final Enumeration<T> enumeration) {
return (ArrayList<T>) of(false, enumeration);
}
/**
* 数组转为一个不可变List<br>
* 类似于Java9中的List.of
*
* @param ts 对象
* @param <T> 对象类型
* @return 不可修改List
*/
@SafeVarargs
public static <T> List<T> view(final T... ts) {
return view(of(ts));
}
/**
* 转为一个不可变List<br>
* 类似于Java9中的List.of
*
* @param ts 对象
* @param <T> 对象类型
* @return 不可修改List如果提供List为{@code null}或者空返回{@link Collections#emptyList()}
*/
public static <T> List<T> view(final List<T> ts) {
if (ArrayUtil.isEmpty(ts)) {
return empty();
}
return Collections.unmodifiableList(ts);
}
/**
* 获取一个空List这个空List不可变
*
* @param <T> 元素类型
* @return 空的List
* @see Collections#emptyList()
* @since 5.2.6
*/
public static <T> List<T> empty() {
return Collections.emptyList();
}
/**
* 新建一个CopyOnWriteArrayList
*
* @param <T> 集合元素类型
* @param collection 集合
* @return {@link CopyOnWriteArrayList}
*/
public static <T> CopyOnWriteArrayList<T> ofCopyOnWrite(final Collection<T> collection) {
return (null == collection) ? (new CopyOnWriteArrayList<>()) : (new CopyOnWriteArrayList<>(collection));
}
/**
* 新建一个CopyOnWriteArrayList
*
* @param <T> 集合元素类型
* @param ts 集合
* @return {@link CopyOnWriteArrayList}
*/
@SafeVarargs
public static <T> CopyOnWriteArrayList<T> ofCopyOnWrite(final T... ts) {
return (null == ts) ? (new CopyOnWriteArrayList<>()) : (new CopyOnWriteArrayList<>(ts));
}
/**
@ -255,7 +255,7 @@ public class ListUtil {
// 每页条目数大于总数直接返回所有
if (resultSize <= pageSize) {
if (pageNo < (PageUtil.getFirstPageNo() + 1)) {
return unmodifiable(list);
return view(list);
} else {
// 越界直接返回空
return new ArrayList<>(0);
@ -500,33 +500,6 @@ public class ListUtil {
return CollUtil.indexOfAll(list, matcher);
}
/**
* 将对应List转换为不可修改的List
*
* @param list List
* @param <T> 元素类型
* @return 不可修改List
* @since 5.2.6
*/
public static <T> List<T> unmodifiable(final List<T> list) {
if (null == list) {
return null;
}
return Collections.unmodifiableList(list);
}
/**
* 获取一个空List这个空List不可变
*
* @param <T> 元素类型
* @return 空的List
* @see Collections#emptyList()
* @since 5.2.6
*/
public static <T> List<T> empty() {
return Collections.emptyList();
}
/**
* 通过传入分区长度将指定列表分区为不同的块每块区域的长度相同最后一块可能小于长度<br>
* 分区是在原List的基础上进行的返回的分区是不可变的抽象列表原列表元素变更分区中元素也会变更

View File

@ -0,0 +1,139 @@
package cn.hutool.core.collection;
import java.io.IOException;
import java.io.Serializable;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Stream;
/**
* 基于Map的Set实现
*
* @param <E> 元素类型
* @author guava
*/
public class SetFromMap<E> extends AbstractSet<E> implements Serializable {
private static final long serialVersionUID = 1L;
private final Map<E, Boolean> m; // The backing map
private transient Set<E> s; // Its keySet
public SetFromMap(final Map<E, Boolean> map) {
m = map;
s = map.keySet();
}
@Override
public void clear() {
m.clear();
}
@Override
public int size() {
return m.size();
}
@Override
public boolean isEmpty() {
return m.isEmpty();
}
@SuppressWarnings("SuspiciousMethodCalls")
@Override
public boolean contains(final Object o) {
return m.containsKey(o);
}
@Override
public boolean remove(final Object o) {
return m.remove(o) != null;
}
@Override
public boolean add(final E e) {
return m.put(e, Boolean.TRUE) == null;
}
@Override
public Iterator<E> iterator() {
return s.iterator();
}
@Override
public Object[] toArray() {
return s.toArray();
}
@SuppressWarnings("SuspiciousToArrayCall")
@Override
public <T> T[] toArray(final T[] a) {
return super.toArray(a);
}
@Override
public String toString() {
return s.toString();
}
@Override
public int hashCode() {
return s.hashCode();
}
@SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
@Override
public boolean equals(final Object o) {
return o == this || s.equals(o);
}
@Override
public boolean containsAll(final Collection<?> c) {
return s.containsAll(c);
}
@Override
public boolean removeAll(final Collection<?> c) {
return s.removeAll(c);
}
@Override
public boolean retainAll(final Collection<?> c) {
return s.retainAll(c);
}
@Override
public void forEach(final Consumer<? super E> action) {
s.forEach(action);
}
@Override
public boolean removeIf(final Predicate<? super E> filter) {
return s.removeIf(filter);
}
@Override
public Spliterator<E> spliterator() {
return s.spliterator();
}
@Override
public Stream<E> stream() {
return s.stream();
}
@Override
public Stream<E> parallelStream() {
return s.parallelStream();
}
private void readObject(final java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
s = m.keySet();
}
}

View File

@ -0,0 +1,195 @@
package cn.hutool.core.collection;
import cn.hutool.core.util.ArrayUtil;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
/**
* 集合中的{@link java.util.Set}相关方法封装
*
* @author looly
*/
public class SetUtil {
/**
* 新建一个List<br>
* 如果提供的初始化数组为空新建默认初始长度的List
*
* @param <T> 集合元素类型
* @param isLinked 是否为链表
* @return List对象
*/
public static <T> HashSet<T> of(final boolean isLinked) {
return _of(isLinked, null);
}
/**
* 新建一个HashSet
*
* @param <T> 集合元素类型
* @param ts 元素数组
* @return HashSet对象
*/
@SafeVarargs
public static <T> HashSet<T> of(final T... ts) {
return _of(false, ts);
}
/**
* 新建一个LinkedHashSet
*
* @param <T> 集合元素类型
* @param ts 元素数组
* @return HashSet对象
* @since 4.1.10
*/
@SafeVarargs
public static <T> LinkedHashSet<T> ofLinked(final T... ts) {
return (LinkedHashSet<T>) _of(true, ts);
}
/**
* 新建一个HashSet
*
* @param <T> 集合元素类型
* @param iterable 集合
* @return HashSet对象
*/
public static <T> HashSet<T> of(final Iterable<T> iterable) {
return of(false, iterable);
}
/**
* 新建一个HashSet<br>
* 提供的参数为null时返回空{@link HashSet}
*
* @param <T> 集合元素类型
* @param isLinked 是否新建LinkedList
* @param iterable {@link Iterable}
* @return HashSet对象
*/
public static <T> HashSet<T> of(final boolean isLinked, final Iterable<T> iterable) {
if (null == iterable) {
return of(isLinked);
}
if (iterable instanceof Collection) {
final Collection<T> collection = (Collection<T>) iterable;
return isLinked ? new LinkedHashSet<>(collection) : new HashSet<>(collection);
}
return of(isLinked, iterable.iterator());
}
/**
* 新建一个HashSet
*
* @param <T> 集合元素类型
* @param isSorted 是否有序有序返回 {@link LinkedHashSet}否则返回{@link HashSet}
* @param iter {@link Iterator}
* @return HashSet对象
* @since 3.0.8
*/
public static <T> HashSet<T> of(final boolean isSorted, final Iterator<T> iter) {
if (null == iter) {
return _of(isSorted, null);
}
final HashSet<T> set = isSorted ? new LinkedHashSet<>() : new HashSet<>();
while (iter.hasNext()) {
set.add(iter.next());
}
return set;
}
/**
* 新建一个HashSet
*
* @param <T> 集合元素类型
* @param isLinked 是否有序有序返回 {@link LinkedHashSet}否则返回{@link HashSet}
* @param enumeration {@link Enumeration}
* @return HashSet对象
* @since 3.0.8
*/
public static <T> HashSet<T> of(final boolean isLinked, final Enumeration<T> enumeration) {
if (null == enumeration) {
return _of(isLinked, null);
}
final HashSet<T> set = isLinked ? new LinkedHashSet<>() : new HashSet<>();
while (enumeration.hasMoreElements()) {
set.add(enumeration.nextElement());
}
return set;
}
/**
* 新建一个SetFromMap
*
* @param <T> 集合元素类型
* @param map Map
* @return SetFromMap对象
*/
public static <T> SetFromMap<T> of(final Map<T, Boolean> map) {
return new SetFromMap<>(map);
}
/**
* 数组转为一个不可变List<br>
* 类似于Java9中的List.of
*
* @param ts 对象
* @param <T> 对象类型
* @return 不可修改List
*/
@SafeVarargs
public static <T> Set<T> view(final T... ts) {
return view(of(ts));
}
/**
* 转为一个不可变Set
*
* @param ts 对象
* @param <T> 对象类型
* @return 不可修改List如果提供List为{@code null}或者空返回{@link Collections#emptySet()}
*/
public static <T> Set<T> view(final Set<T> ts) {
if (ArrayUtil.isEmpty(ts)) {
return empty();
}
return Collections.unmodifiableSet(ts);
}
/**
* 获取一个空Set这个空Set不可变
*
* @param <T> 元素类型
* @return 空的List
* @see Collections#emptySet()
*/
public static <T> Set<T> empty() {
return Collections.emptySet();
}
/**
* 新建一个HashSet
*
* @param <T> 集合元素类型
* @param isLinked 是否有序有序返回 {@link LinkedHashSet}否则返回 {@link HashSet}
* @param ts 元素数组
* @return HashSet对象
*/
private static <T> HashSet<T> _of(final boolean isLinked, final T[] ts) {
if (ArrayUtil.isEmpty(ts)) {
return isLinked ? new LinkedHashSet<>() : new HashSet<>();
}
final int initialCapacity = Math.max((int) (ts.length / .75f) + 1, 16);
final HashSet<T> set = isLinked ? new LinkedHashSet<>(initialCapacity) : new HashSet<>(initialCapacity);
Collections.addAll(set, ts);
return set;
}
}

View File

@ -44,7 +44,7 @@ public class CopiedIter<E> implements IterableIter<E>, Serializable {
* @param iterator 被复制的Iterator
*/
public CopiedIter(final Iterator<E> iterator) {
final List<E> eleList = ListUtil.toList(iterator);
final List<E> eleList = ListUtil.of(iterator);
this.listIterator = eleList.iterator();
}

View File

@ -519,7 +519,7 @@ public class IterUtil {
* @since 4.0.6
*/
public static <E> List<E> toList(final Iterator<E> iter) {
return ListUtil.toList(iter);
return ListUtil.of(iter);
}
/**
@ -710,7 +710,7 @@ public class IterUtil {
* @return 编辑后的集合
* @since 4.6.5
*/
public static <T extends Iterable<E>, E> T filter(final T iter, final Filter<E> filter) {
public static <T extends Iterable<E>, E> T filter(final T iter, final Predicate<E> filter) {
if (null == iter) {
return null;
}
@ -734,13 +734,13 @@ public class IterUtil {
* @return 编辑后的集合
* @since 4.6.5
*/
public static <E> Iterator<E> filter(final Iterator<E> iter, final Filter<E> filter) {
public static <E> Iterator<E> filter(final Iterator<E> iter, final Predicate<E> filter) {
if (null == iter || null == filter) {
return iter;
}
while (iter.hasNext()) {
if (false == filter.accept(iter.next())) {
if (false == filter.test(iter.next())) {
iter.remove();
}
}

View File

@ -1,7 +1,10 @@
package cn.hutool.core.compiler;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.compress.ZipUtil;
import cn.hutool.core.io.resource.FileResource;
import cn.hutool.core.io.resource.Resource;
import javax.tools.JavaFileObject;
import java.io.File;
@ -17,26 +20,59 @@ import java.util.zip.ZipFile;
*/
public class JavaFileObjectUtil {
/**
* 获取指定资源下的所有待编译的java源码文件并以{@link JavaFileObject}形式返回
* <ul>
* <li>如果资源为目录则遍历目录找到目录中的.java或者.jar等文件加载之</li>
* <li>如果资源为.jar或.zip等解压读取其中的.java文件加载之</li>
* <li>其他情况直接读取资源流并加载之</li>
* </ul>
*
* @param resource 资源可以为目录文件或流
* @return 所有待编译的 {@link JavaFileObject}
*/
public static List<JavaFileObject> getJavaFileObjects(final Resource resource) {
final List<JavaFileObject> result = new ArrayList<>();
if (resource instanceof FileResource) {
final File file = ((FileResource) resource).getFile();
result.addAll(JavaFileObjectUtil.getJavaFileObjects(file));
} else {
result.add(new JavaSourceFileObject(resource.getName(), resource.getStream()));
}
return result;
}
/**
* 获取指定文件下的所有待编译的java文件并以{@link JavaFileObject}形式返回
* <ul>
* <li>如果文件为目录则遍历目录找到目录中的.java或者.jar等文件加载之</li>
* <li>如果文件为.jar或.zip等解压读取其中的.java文件加载之</li>
* </ul>
*
* @param file 文件或目录文件支持.java.jar和.zip文件
* @return 所有待编译的 {@link JavaFileObject}
*/
public static List<JavaFileObject> getJavaFileObjects(final File file) {
final List<JavaFileObject> result = new ArrayList<>();
final String fileName = file.getName();
if (isJavaFile(fileName)) {
result.add(new JavaSourceFileObject(file.toURI()));
} else if (isJarOrZipFile(fileName)) {
result.addAll(getJavaFileObjectByZipOrJarFile(file));
if (file.isDirectory()) {
FileUtil.walkFiles(file, (subFile) -> result.addAll(getJavaFileObjects(file)));
} else {
final String fileName = file.getName();
if (isJavaFile(fileName)) {
result.add(new JavaSourceFileObject(file.toURI()));
} else if (isJarOrZipFile(fileName)) {
result.addAll(getJavaFileObjectByZipOrJarFile(file));
}
}
return result;
}
/**
* 是否是jar zip 文件
* 是否是jar zip 文件<br>
* 通过扩展名判定
*
* @param fileName 文件名
* @return 是否是jar zip 文件
@ -46,7 +82,8 @@ public class JavaFileObjectUtil {
}
/**
* 是否是java文件
* 是否是java文件<br>
* 通过扩展名判定
*
* @param fileName 文件名
* @return 是否是.java文件

View File

@ -1,5 +1,6 @@
package cn.hutool.core.compiler;
import cn.hutool.core.classloader.ClassLoaderUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
@ -7,11 +8,9 @@ import cn.hutool.core.io.resource.FileResource;
import cn.hutool.core.io.resource.Resource;
import cn.hutool.core.io.resource.StringResource;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.classloader.ClassLoaderUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.net.URLUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjUtil;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler.CompilationTask;
@ -22,11 +21,8 @@ import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Java 源码编译器
@ -230,40 +226,9 @@ public class JavaSourceCompiler {
final List<JavaFileObject> list = new ArrayList<>();
for (final Resource resource : this.sourceList) {
if (resource instanceof FileResource) {
final File file = ((FileResource) resource).getFile();
FileUtil.walkFiles(file, (subFile) -> list.addAll(JavaFileObjectUtil.getJavaFileObjects(file)));
} else {
list.add(new JavaSourceFileObject(resource.getName(), resource.getStream()));
}
list.addAll(JavaFileObjectUtil.getJavaFileObjects(resource));
}
return list;
}
/**
* 通过源码Map获得Java文件对象
*
* @param sourceCodeMap 源码Map
* @return Java文件对象集合
*/
private Collection<JavaFileObject> getJavaFileObjectByMap(final Map<String, String> sourceCodeMap) {
if (MapUtil.isNotEmpty(sourceCodeMap)) {
return sourceCodeMap.entrySet().stream()
.map(entry -> new JavaSourceFileObject(entry.getKey(), entry.getValue(), CharsetUtil.UTF_8))
.collect(Collectors.toList());
}
return Collections.emptySet();
}
/**
* 通过.java文件创建Java文件对象
*
* @param file .java文件
* @return Java文件对象
*/
private JavaFileObject getJavaFileObjectByJavaFile(final File file) {
return new JavaSourceFileObject(file.toURI());
}
}

View File

@ -1,9 +1,9 @@
package cn.hutool.core.convert;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.CharUtil;
import cn.hutool.core.reflect.ClassUtil;
import cn.hutool.core.text.StrUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.CharUtil;
import java.io.Serializable;
import java.util.Map;

View File

@ -0,0 +1,113 @@
package cn.hutool.core.convert;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 转换工具类提供集合Map等向上向下转换工具
*
* @author feg545
* @since 5.8.1
*/
public class CastUtil {
/**
* 泛型集合向上转型例如将Collection&lt;Integer&gt;转换为Collection&lt;Number&gt;
*
* @param collection 集合
* @param <T> 元素类型
* @return 转换后的集合
*/
@SuppressWarnings("unchecked")
public static <T> Collection<T> castUp(Collection<? extends T> collection) {
return (Collection<T>) collection;
}
/**
* 泛型集合向下转型例如将Collection&lt;Number&gt;转换为Collection&lt;Integer&gt;
*
* @param collection 集合
* @param <T> 元素类型
* @return 转换后的集合
*/
@SuppressWarnings("unchecked")
public static <T> Collection<T> castDown(Collection<? super T> collection) {
return (Collection<T>) collection;
}
/**
* 泛型集合向上转型例如将Set&lt;Integer&gt;转换为Set&lt;Number&gt;
*
* @param set 集合
* @param <T> 泛型
* @return 泛化集合
*/
@SuppressWarnings("unchecked")
public static <T> Set<T> castUp(Set<? extends T> set) {
return (Set<T>) set;
}
/**
* 泛型集合向下转型例如将Set&lt;Number&gt;转换为Set&lt;Integer&gt;
*
* @param set 集合
* @param <T> 泛型子类
* @return 泛化集合
*/
@SuppressWarnings("unchecked")
public static <T> Set<T> castDown(Set<? super T> set) {
return (Set<T>) set;
}
/**
* 泛型接口向上转型例如将List&lt;Integer&gt;转换为List&lt;Number&gt;
*
* @param list 集合
* @param <T> 泛型的父类
* @return 泛化集合
*/
@SuppressWarnings("unchecked")
public static <T> List<T> castUp(List<? extends T> list) {
return (List<T>) list;
}
/**
* 泛型集合向下转型例如将List&lt;Number&gt;转换为List&lt;Integer&gt;
*
* @param list 集合
* @param <T> 泛型的子类
* @return 泛化集合
*/
@SuppressWarnings("unchecked")
public static <T> List<T> castDown(List<? super T> list) {
return (List<T>) list;
}
/**
* 泛型集合向下转型例如将Map&lt;Integer, Integer&gt;转换为Map&lt;Number,Number&gt;
*
* @param map 集合
* @param <K> 泛型父类
* @param <V> 泛型父类
* @return 泛化集合
*/
@SuppressWarnings("unchecked")
public static <K, V> Map<K, V> castUp(Map<? extends K, ? extends V> map) {
return (Map<K, V>) map;
}
/**
* 泛型集合向下转型例如将Map&lt;Number,Number&gt;转换为Map&lt;Integer, Integer&gt;
*
* @param map 集合
* @param <K> 泛型子类
* @param <V> 泛型子类
* @return 泛化集合
*/
@SuppressWarnings("unchecked")
public static <K, V> Map<K, V> castDown(Map<? super K, ? super V> map) {
return (Map<K, V>) map;
}
}

View File

@ -258,6 +258,7 @@ public class ConverterRegistry implements Serializable {
return converter.convert(value, defaultValue);
}
Class<T> rowType = (Class<T>) TypeUtil.getClass(type);
if (null == rowType) {
if (null != defaultValue) {

View File

@ -63,7 +63,7 @@ public class NumberWordFormatter {
int index = -1;
double res = value;
while (res > 10 && (false == isTwo || index < 1)) {
if (res > 1000) {
if (res >= 1000) {
res = res / 1000;
index++;
}

View File

@ -3,8 +3,8 @@ package cn.hutool.core.convert.impl;
import cn.hutool.core.convert.AbstractConverter;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.text.StrUtil;
import cn.hutool.core.util.ObjUtil;
import java.time.Instant;
import java.time.LocalDate;
@ -84,6 +84,12 @@ public class TemporalAccessorConverter extends AbstractConverter<TemporalAccesso
this.format = format;
}
@SuppressWarnings("unchecked")
@Override
public Class<TemporalAccessor> getTargetType() {
return (Class<TemporalAccessor>) this.targetType;
}
@Override
protected TemporalAccessor convertInternal(final Object value) {
if (value instanceof Long) {

View File

@ -1,17 +1,17 @@
package cn.hutool.core.date;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.comparator.CompareUtil;
import cn.hutool.core.date.format.DateParser;
import cn.hutool.core.date.format.DatePrinter;
import cn.hutool.core.date.format.FastDateFormat;
import cn.hutool.core.date.format.GlobalCustomFormat;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.regex.PatternPool;
import cn.hutool.core.util.CharUtil;
import cn.hutool.core.math.NumberUtil;
import cn.hutool.core.regex.PatternPool;
import cn.hutool.core.regex.ReUtil;
import cn.hutool.core.text.StrUtil;
import cn.hutool.core.util.CharUtil;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
@ -20,7 +20,14 @@ import java.time.LocalDateTime;
import java.time.Year;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
@ -1842,8 +1849,8 @@ public class DateUtil extends CalendarUtil {
* @since 5.7.21
*/
public static List<DateTime> rangeContains(final DateRange start, final DateRange end) {
final List<DateTime> startDateTimes = CollUtil.newArrayList((Iterable<DateTime>) start);
final List<DateTime> endDateTimes = CollUtil.newArrayList((Iterable<DateTime>) end);
final List<DateTime> startDateTimes = ListUtil.of((Iterable<DateTime>) start);
final List<DateTime> endDateTimes = ListUtil.of((Iterable<DateTime>) end);
return startDateTimes.stream().filter(endDateTimes::contains).collect(Collectors.toList());
}
@ -1857,8 +1864,8 @@ public class DateUtil extends CalendarUtil {
* @since 5.7.21
*/
public static List<DateTime> rangeNotContains(final DateRange start, final DateRange end) {
final List<DateTime> startDateTimes = CollUtil.newArrayList((Iterable<DateTime>) start);
final List<DateTime> endDateTimes = CollUtil.newArrayList((Iterable<DateTime>) end);
final List<DateTime> startDateTimes = ListUtil.of((Iterable<DateTime>) start);
final List<DateTime> endDateTimes = ListUtil.of((Iterable<DateTime>) end);
return endDateTimes.stream().filter(item -> !startDateTimes.contains(item)).collect(Collectors.toList());
}
@ -1909,7 +1916,7 @@ public class DateUtil extends CalendarUtil {
* @return {@link DateRange}
*/
public static List<DateTime> rangeToList(final Date start, final Date end, final DateField unit) {
return CollUtil.newArrayList((Iterable<DateTime>) range(start, end, unit));
return ListUtil.of((Iterable<DateTime>) range(start, end, unit));
}
/**
@ -1923,7 +1930,7 @@ public class DateUtil extends CalendarUtil {
* @since 5.7.16
*/
public static List<DateTime> rangeToList(final Date start, final Date end, final DateField unit, final int step) {
return CollUtil.newArrayList((Iterable<DateTime>) new DateRange(start, end, unit, step));
return ListUtil.of((Iterable<DateTime>) new DateRange(start, end, unit, step));
}
/**

View File

@ -1,9 +1,10 @@
package cn.hutool.core.date.chinese;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.map.TableMap;
import java.util.List;
import java.util.Map;
/**
* 节假日农历封装
@ -15,72 +16,72 @@ public class LunarFestival {
//农历节日 *表示放假日
// 来自https://baike.baidu.com/item/%E4%B8%AD%E5%9B%BD%E4%BC%A0%E7%BB%9F%E8%8A%82%E6%97%A5/396100
private static final TableMap<Pair<Integer, Integer>, String> L_FTV = new TableMap<>(16);
private static final TableMap<Map.Entry<Integer, Integer>, String> L_FTV = new TableMap<>(16);
static {
// 节日
L_FTV.put(new Pair<>(1, 1), "春节");
L_FTV.put(new Pair<>(1, 2), "犬日");
L_FTV.put(new Pair<>(1, 3), "猪日");
L_FTV.put(new Pair<>(1, 4), "羊日");
L_FTV.put(new Pair<>(1, 5), "牛日 破五日");
L_FTV.put(new Pair<>(1, 6), "马日 送穷日");
L_FTV.put(new Pair<>(1, 7), "人日 人胜节");
L_FTV.put(new Pair<>(1, 8), "谷日 八仙日");
L_FTV.put(new Pair<>(1, 9), "天日 九皇会");
L_FTV.put(new Pair<>(1, 10), "地日 石头生日");
L_FTV.put(new Pair<>(1, 12), "火日 老鼠娶媳妇日");
L_FTV.put(new Pair<>(1, 13), "上(试)灯日 关公升天日");
L_FTV.put(new Pair<>(1, 15), "元宵节 上元节");
L_FTV.put(new Pair<>(1, 18), "落灯日");
L_FTV.put(MapUtil.entry(1, 1), "春节");
L_FTV.put(MapUtil.entry(1, 2), "犬日");
L_FTV.put(MapUtil.entry(1, 3), "猪日");
L_FTV.put(MapUtil.entry(1, 4), "羊日");
L_FTV.put(MapUtil.entry(1, 5), "牛日 破五日");
L_FTV.put(MapUtil.entry(1, 6), "马日 送穷日");
L_FTV.put(MapUtil.entry(1, 7), "人日 人胜节");
L_FTV.put(MapUtil.entry(1, 8), "谷日 八仙日");
L_FTV.put(MapUtil.entry(1, 9), "天日 九皇会");
L_FTV.put(MapUtil.entry(1, 10), "地日 石头生日");
L_FTV.put(MapUtil.entry(1, 12), "火日 老鼠娶媳妇日");
L_FTV.put(MapUtil.entry(1, 13), "上(试)灯日 关公升天日");
L_FTV.put(MapUtil.entry(1, 15), "元宵节 上元节");
L_FTV.put(MapUtil.entry(1, 18), "落灯日");
// 二月
L_FTV.put(new Pair<>(2, 1), "中和节 太阳生日");
L_FTV.put(new Pair<>(2, 2), "龙抬头");
L_FTV.put(new Pair<>(2, 12), "花朝节");
L_FTV.put(new Pair<>(2, 19), "观世音圣诞");
L_FTV.put(MapUtil.entry(2, 1), "中和节 太阳生日");
L_FTV.put(MapUtil.entry(2, 2), "龙抬头");
L_FTV.put(MapUtil.entry(2, 12), "花朝节");
L_FTV.put(MapUtil.entry(2, 19), "观世音圣诞");
// 三月
L_FTV.put(new Pair<>(3, 3), "上巳节");
L_FTV.put(MapUtil.entry(3, 3), "上巳节");
// 四月
L_FTV.put(new Pair<>(4, 1), "祭雹神");
L_FTV.put(new Pair<>(4, 4), "文殊菩萨诞辰");
L_FTV.put(new Pair<>(4, 8), "佛诞节");
L_FTV.put(MapUtil.entry(4, 1), "祭雹神");
L_FTV.put(MapUtil.entry(4, 4), "文殊菩萨诞辰");
L_FTV.put(MapUtil.entry(4, 8), "佛诞节");
// 五月
L_FTV.put(new Pair<>(5, 5), "端午节 端阳节");
L_FTV.put(MapUtil.entry(5, 5), "端午节 端阳节");
// 六月
L_FTV.put(new Pair<>(6, 6), "晒衣节 姑姑节");
L_FTV.put(new Pair<>(6, 6), "天贶节");
L_FTV.put(new Pair<>(6, 24), "彝族火把节");
L_FTV.put(MapUtil.entry(6, 6), "晒衣节 姑姑节");
L_FTV.put(MapUtil.entry(6, 6), "天贶节");
L_FTV.put(MapUtil.entry(6, 24), "彝族火把节");
// 七月
L_FTV.put(new Pair<>(7, 7), "七夕");
L_FTV.put(new Pair<>(7, 14), "鬼节(南方)");
L_FTV.put(new Pair<>(7, 15), "中元节");
L_FTV.put(new Pair<>(7, 15), "盂兰盆节 中元节");
L_FTV.put(new Pair<>(7, 30), "地藏节");
L_FTV.put(MapUtil.entry(7, 7), "七夕");
L_FTV.put(MapUtil.entry(7, 14), "鬼节(南方)");
L_FTV.put(MapUtil.entry(7, 15), "中元节");
L_FTV.put(MapUtil.entry(7, 15), "盂兰盆节 中元节");
L_FTV.put(MapUtil.entry(7, 30), "地藏节");
// 八月
L_FTV.put(new Pair<>(8, 15), "中秋节");
L_FTV.put(MapUtil.entry(8, 15), "中秋节");
// 九月
L_FTV.put(new Pair<>(9, 9), "重阳节");
L_FTV.put(MapUtil.entry(9, 9), "重阳节");
// 十月
L_FTV.put(new Pair<>(10, 1), "祭祖节");
L_FTV.put(new Pair<>(10, 15), "下元节");
L_FTV.put(MapUtil.entry(10, 1), "祭祖节");
L_FTV.put(MapUtil.entry(10, 15), "下元节");
// 十一月
L_FTV.put(new Pair<>(11, 17), "阿弥陀佛圣诞");
L_FTV.put(MapUtil.entry(11, 17), "阿弥陀佛圣诞");
// 腊月
L_FTV.put(new Pair<>(12, 8), "腊八节");
L_FTV.put(new Pair<>(12, 16), "尾牙");
L_FTV.put(new Pair<>(12, 23), "小年");
L_FTV.put(new Pair<>(12, 30), "除夕");
L_FTV.put(MapUtil.entry(12, 8), "腊八节");
L_FTV.put(MapUtil.entry(12, 16), "尾牙");
L_FTV.put(MapUtil.entry(12, 23), "小年");
L_FTV.put(MapUtil.entry(12, 30), "除夕");
}
/**
@ -110,6 +111,6 @@ public class LunarFestival {
* @return 获得农历节日
*/
public static List<String> getFestivals(final int month, final int day) {
return L_FTV.getValues(new Pair<>(month, day));
return L_FTV.getValues(MapUtil.entry(month, day));
}
}

View File

@ -0,0 +1,33 @@
package cn.hutool.core.exceptions;
/**
* InvocationTargetException的运行时异常
*
* @author looly
*/
public class InvocationTargetRuntimeException extends UtilException {
public InvocationTargetRuntimeException(final Throwable e) {
super(e);
}
public InvocationTargetRuntimeException(final String message) {
super(message);
}
public InvocationTargetRuntimeException(final String messageTemplate, final Object... params) {
super(messageTemplate, params);
}
public InvocationTargetRuntimeException(final String message, final Throwable throwable) {
super(message, throwable);
}
public InvocationTargetRuntimeException(final String message, final Throwable throwable, final boolean enableSuppression, final boolean writableStackTrace) {
super(message, throwable, enableSuppression, writableStackTrace);
}
public InvocationTargetRuntimeException(final Throwable throwable, final String messageTemplate, final Object... params) {
super(throwable, messageTemplate, params);
}
}

View File

@ -190,6 +190,9 @@ public class FileTypeUtil {
} else if ("docx".equalsIgnoreCase(extName)) {
// issue#I47JGH
typeName = "docx";
} else if ("pptx".equalsIgnoreCase(extName)) {
// issue#I5A0GO
typeName = "pptx";
}
}
return typeName;

View File

@ -1097,7 +1097,7 @@ public class FileUtil extends PathUtil {
* 情况如下
*
* <pre>
* 1src和dest都为目录src下所有文件目录拷贝到dest下
* 1src和dest都为目录src下所有文件目录拷贝到dest下
* 2src和dest都为文件直接复制名字为dest
* 3src为文件dest为目录将src拷贝到dest目录下
* </pre>
@ -1117,7 +1117,7 @@ public class FileUtil extends PathUtil {
* 情况如下
*
* <pre>
* 1src和dest都为目录src下所有文件包括子目录拷贝到dest下
* 1src和dest都为目录src下所有文件包括子目录拷贝到dest下
* 2src和dest都为文件直接复制名字为dest
* 3src为文件dest为目录将src拷贝到dest目录下
* </pre>

View File

@ -1,6 +1,6 @@
package cn.hutool.core.io.resource;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.IORuntimeException;
import java.io.BufferedReader;
@ -32,7 +32,7 @@ public class MultiResource implements Resource, Iterable<Resource>, Iterator<Res
* @param resources 资源数组
*/
public MultiResource(final Resource... resources) {
this(CollUtil.newArrayList(resources));
this(ListUtil.of(resources));
}
/**
@ -44,7 +44,7 @@ public class MultiResource implements Resource, Iterable<Resource>, Iterator<Res
if(resources instanceof List) {
this.resources = (List<Resource>)resources;
}else {
this.resources = CollUtil.newArrayList(resources);
this.resources = ListUtil.of(resources);
}
}

View File

@ -1,6 +1,6 @@
package cn.hutool.core.io.watch.watchers;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.watch.Watcher;
import cn.hutool.core.lang.Chain;
@ -35,7 +35,7 @@ public class WatcherChain implements Watcher, Chain<Watcher, WatcherChain>{
* @param watchers 观察者列表
*/
public WatcherChain(final Watcher... watchers) {
chain = CollUtil.newArrayList(watchers);
chain = ListUtil.of(watchers);
}
@Override

View File

@ -1,87 +0,0 @@
package cn.hutool.core.lang;
import cn.hutool.core.clone.CloneSupport;
import java.io.Serializable;
import java.util.Objects;
/**
* 键值对对象只能在构造时传入键值
*
* @param <K> 键类型
* @param <V> 值类型
* @author looly
* @since 4.1.5
*/
public class Pair<K, V> extends CloneSupport<Pair<K, V>> implements Serializable {
private static final long serialVersionUID = 1L;
protected K key;
protected V value;
/**
* 构建{@code Pair}对象
*
* @param <K> 键类型
* @param <V> 值类型
* @param key
* @param value
* @return {@code Pair}
* @since 5.4.3
*/
public static <K, V> Pair<K, V> of(final K key, final V value) {
return new Pair<>(key, value);
}
/**
* 构造
*
* @param key
* @param value
*/
public Pair(final K key, final V value) {
this.key = key;
this.value = value;
}
/**
* 获取键
*
* @return
*/
public K getKey() {
return this.key;
}
/**
* 获取值
*
* @return
*/
public V getValue() {
return this.value;
}
@Override
public String toString() {
return "Pair [key=" + key + ", value=" + value + "]";
}
@Override
public boolean equals(final Object o) {
if (this == o)
return true;
if (o instanceof Pair) {
final Pair<?, ?> pair = (Pair<?, ?>) o;
return Objects.equals(getKey(), pair.getKey()) &&
Objects.equals(getValue(), pair.getValue());
}
return false;
}
@Override
public int hashCode() {
//copy from 1.8 HashMap.Node
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
}

View File

@ -52,7 +52,16 @@ public final class Singleton {
*/
@SuppressWarnings("unchecked")
public static <T> T get(final String key, final Func0<T> supplier) {
return (T) POOL.computeIfAbsent(key, (k)-> supplier.callWithRuntimeException());
//return (T) POOL.computeIfAbsent(key, (k)-> supplier.callWithRuntimeException());
// issues#2349
// ConcurrentHashMap.computeIfAbsent在某些情况下会导致死循环问题此处采用Dubbo的解决方案
Object value = POOL.get(key);
if(null == value){
POOL.putIfAbsent(key, supplier.callWithRuntimeException());
value = POOL.get(key);
}
return (T) value;
}
/**

View File

@ -64,7 +64,7 @@ public class Tuple extends CloneSupport<Tuple> implements Iterable<Object>, Seri
* @since 5.6.6
*/
public final List<Object> toList() {
return ListUtil.toList(this.members);
return ListUtil.of(this.members);
}
/**

View File

@ -0,0 +1,87 @@
package cn.hutool.core.lang.mutable;
import cn.hutool.core.map.AbsEntry;
import java.io.Serializable;
import java.util.Map;
/**
* 可变键和值的{@link Map.Entry}实现可以修改键和值
*
* @param <K> 键类型
* @param <V> 值类型
* @author looly
*/
public class MutableEntry<K, V> extends AbsEntry<K, V> implements Mutable<Map.Entry<K, V>>, Serializable {
private static final long serialVersionUID = 1L;
protected K key;
protected V value;
/**
* 构造
*
* @param key
* @param value
*/
public MutableEntry(final K key, final V value) {
this.key = key;
this.value = value;
}
/**
* 获取键
*
* @return
*/
@Override
public K getKey() {
return this.key;
}
/**
* 获取值
*
* @return
*/
@Override
public V getValue() {
return this.value;
}
/**
* 设置键
*
* @param key 新键
* @return old key
*/
public K setKey(final K key) {
final K oldKey = this.key;
this.key = key;
return oldKey;
}
/**
* 设置值
*
* @param value 新值
* @return old value
*/
@Override
public V setValue(final V value) {
final V oldValue = this.value;
this.value = value;
return oldValue;
}
@Override
public Map.Entry<K, V> get() {
return this;
}
@Override
public void set(final Map.Entry<K, V> pair) {
this.key = pair.getKey();
this.value = pair.getValue();
}
}

View File

@ -1,57 +0,0 @@
package cn.hutool.core.lang.mutable;
import cn.hutool.core.lang.Pair;
/**
* 可变{@link Pair}实现可以修改键和值
*
* @param <K> 键类型
* @param <V> 值类型
* @since 5.7.16
*/
public class MutablePair<K, V> extends Pair<K, V> implements Mutable<Pair<K, V>>{
private static final long serialVersionUID = 1L;
/**
* 构造
*
* @param key
* @param value
*/
public MutablePair(final K key, final V value) {
super(key, value);
}
/**
* 设置键
*
* @param key 新键
* @return this
*/
public MutablePair<K, V> setKey(final K key) {
this.key = key;
return this;
}
/**
* 设置值
*
* @param value 新值
* @return this
*/
public MutablePair<K, V> setValue(final V value) {
this.value = value;
return this;
}
@Override
public Pair<K, V> get() {
return this;
}
@Override
public void set(final Pair<K, V> pair) {
this.key = pair.getKey();
this.value = pair.getValue();
}
}

View File

@ -2,10 +2,10 @@ package cn.hutool.core.map;
import cn.hutool.core.bean.BeanPath;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.SetUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.lang.func.Func0;
import cn.hutool.core.lang.func.LambdaUtil;
import cn.hutool.core.lang.getter.BasicTypeGetter;
@ -61,16 +61,15 @@ public class Dict extends LinkedHashMap<String, Object> implements BasicTypeGett
}
/**
* 根据给定的Pair数组创建Dict对象
* 根据给定的Entry数组创建Dict对象
*
* @param pairs 键值对
* @return Dict
* @since 5.4.1
*/
@SafeVarargs
public static Dict of(final Pair<String, Object>... pairs) {
public static Dict ofEntries(final Map.Entry<String, Object>... pairs) {
final Dict dict = create();
for (final Pair<String, Object> pair : pairs) {
for (final Map.Entry<String, Object> pair : pairs) {
dict.put(pair.getKey(), pair.getValue());
}
return dict;
@ -94,7 +93,7 @@ public class Dict extends LinkedHashMap<String, Object> implements BasicTypeGett
* @return Dict
* @since 5.4.1
*/
public static Dict of(final Object... keysAndValues) {
public static Dict ofKvs(final Object... keysAndValues) {
final Dict dict = create();
String key = null;
@ -248,7 +247,7 @@ public class Dict extends LinkedHashMap<String, Object> implements BasicTypeGett
* @return vo
*/
public <T> T toBeanIgnoreCase(final Class<T> clazz) {
return BeanUtil.toBeanIgnoreCase(this, clazz, false);
return BeanUtil.toBean(this, clazz, CopyOptions.create().setIgnoreCase(true));
}
/**
@ -290,7 +289,7 @@ public class Dict extends LinkedHashMap<String, Object> implements BasicTypeGett
* @param withoutNames 不需要去除的字段名
*/
public <T extends Dict> void removeEqual(final T dict, final String... withoutNames) {
final HashSet<String> withoutSet = CollUtil.newHashSet(withoutNames);
final HashSet<String> withoutSet = SetUtil.of(withoutNames);
for (final Map.Entry<String, Object> entry : dict.entrySet()) {
if (withoutSet.contains(entry.getKey())) {
continue;
@ -536,7 +535,7 @@ public class Dict extends LinkedHashMap<String, Object> implements BasicTypeGett
*/
@SuppressWarnings("unchecked")
public <T> T getByPath(final String expression) {
return (T) BeanPath.create(expression).get(this);
return (T) BeanPath.of(expression).get(this);
}
/**

View File

@ -1,6 +1,7 @@
package cn.hutool.core.map;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.func.Editor;
import cn.hutool.core.lang.func.Filter;
@ -408,7 +409,7 @@ public class MapUtil {
key = entry.getKey();
valueList = resultMap.get(key);
if (null == valueList) {
valueList = CollUtil.newArrayList(entry.getValue());
valueList = ListUtil.of(entry.getValue());
resultMap.put(key, valueList);
} else {
valueList.add(entry.getValue());
@ -463,7 +464,7 @@ public class MapUtil {
List<V> vList;
int vListSize;
for (final Entry<K, ? extends Iterable<V>> entry : listMap.entrySet()) {
vList = CollUtil.newArrayList(entry.getValue());
vList = ListUtil.of(entry.getValue());
vListSize = vList.size();
if (index < vListSize) {
map.put(entry.getKey(), vList.get(index));
@ -1411,7 +1412,7 @@ public class MapUtil {
*/
public static <K, V> Map.Entry<K, V> entry(final K key, final V value, final boolean isImmutable) {
return isImmutable ?
new AbstractMap.SimpleEntry<>(key, value) :
new AbstractMap.SimpleImmutableEntry<>(key, value);
new AbstractMap.SimpleImmutableEntry<>(key, value) :
new AbstractMap.SimpleEntry<>(key, value);
}
}

View File

@ -1,7 +1,6 @@
package cn.hutool.core.map;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.func.Func0;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ReferenceUtil;
@ -143,17 +142,6 @@ public class ReferenceConcurrentMap<K, V> implements ConcurrentMap<K, V>, Iterab
return this.raw.computeIfPresent(ofKey(key, this.lastQueue), (kWeakKey, value) -> remappingFunction.apply(key, value));
}
/**
* 从缓存中获得对象当对象不在缓存中或已经过期返回Func0回调产生的对象
*
* @param key
* @param supplier 如果不存在回调方法用于生产值对象
* @return 值对象
*/
public V computeIfAbsent(final K key, final Func0<? extends V> supplier) {
return computeIfAbsent(key, (keyParam) -> supplier.callWithRuntimeException());
}
@SuppressWarnings("unchecked")
@Override
public V remove(final Object key) {

View File

@ -56,8 +56,8 @@ public class TableMap<K, V> implements Map<K, V>, Iterable<Map.Entry<K, V>>, Ser
* @param values 值列表
*/
public TableMap(final K[] keys, final V[] values) {
this.keys = CollUtil.toList(keys);
this.values = CollUtil.toList(values);
this.keys = ListUtil.of(keys);
this.values = ListUtil.of(values);
}
@Override

View File

@ -2,7 +2,6 @@ package cn.hutool.core.math;
import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.math.Calculator;
import cn.hutool.core.text.StrUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.CharUtil;
@ -34,9 +33,10 @@ import java.util.Set;
* </p>
* 相关介绍
* <ul>
* <li>http://www.oschina.net/code/snippet_563112_25237</li>
* <li>https://github.com/venusdrogon/feilong-core/wiki/one-jdk7-bug-thinking</li>
* <li><a href="https://github.com/venusdrogon/feilong-core/wiki/one-jdk7-bug-thinking">one-jdk7-bug-thinking</a></li>
* </ul>
* <p>
* TODO 需整理精简方法去掉无用的重载方法
*
* @author Looly
*/
@ -723,7 +723,7 @@ public class NumberUtil {
if (v1 instanceof BigDecimal && v2 instanceof BigDecimal) {
return div((BigDecimal) v1, (BigDecimal) v2, scale, roundingMode);
}
return div(v1.toString(), v2.toString(), scale, roundingMode);
return div(StrUtil.toStringOrNull(v1), StrUtil.toStringOrNull(v2), scale, roundingMode);
}
/**
@ -1242,6 +1242,9 @@ public class NumberUtil {
* @return 是否为整数
*/
public static boolean isInteger(final String s) {
if(StrUtil.isBlank(s)) {
return false;
}
try {
Integer.parseInt(s);
} catch (final NumberFormatException e) {
@ -1259,6 +1262,9 @@ public class NumberUtil {
* @since 4.0.0
*/
public static boolean isLong(final String s) {
if(StrUtil.isBlank(s)) {
return false;
}
try {
Long.parseLong(s);
} catch (final NumberFormatException e) {
@ -1274,13 +1280,16 @@ public class NumberUtil {
* @return 是否为{@link Double}类型
*/
public static boolean isDouble(final String s) {
if(StrUtil.isBlank(s)) {
return false;
}
try {
Double.parseDouble(s);
return s.contains(".");
} catch (final NumberFormatException ignore) {
// ignore
}
return false;
return true;
}
/**
@ -2454,7 +2463,7 @@ public class NumberUtil {
return 0L;
}
if (number.startsWith("0x")) {
if (StrUtil.startWithIgnoreCase(number, "0x")) {
// 0x04表示16进制数
return Long.parseLong(number.substring(2), 16);
}
@ -2528,6 +2537,11 @@ public class NumberUtil {
* @since 4.1.15
*/
public static Number parseNumber(final String numberStr) throws NumberFormatException {
if (StrUtil.startWithIgnoreCase(numberStr, "0x")) {
// 0x04表示16进制数
return Long.parseLong(numberStr.substring(2), 16);
}
try {
final NumberFormat format = NumberFormat.getInstance();
if (format instanceof DecimalFormat) {

View File

@ -67,7 +67,7 @@ public class Ipv4Util {
final String[] param = StrUtil.splitToArray(ipRange, IP_MASK_SPLIT_MARK);
return list(param[0], Integer.parseInt(param[1]), isAll);
} else {
return ListUtil.toList(ipRange);
return ListUtil.of(ipRange);
}
}

View File

@ -16,7 +16,6 @@ import cn.hutool.core.util.CharsetUtil;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.net.URI;
import java.net.URL;
@ -461,16 +460,6 @@ public class ClassUtil {
}
}
/**
* 是否为抽象类
*
* @param clazz
* @return 是否为抽象类
*/
public static boolean isAbstract(final Class<?> clazz) {
return Modifier.isAbstract(clazz.getModifiers());
}
/**
* 是否为标准的类<br>
* 这个类必须
@ -490,7 +479,7 @@ public class ClassUtil {
public static boolean isNormalClass(final Class<?> clazz) {
return null != clazz //
&& false == clazz.isInterface() //
&& false == isAbstract(clazz) //
&& false == ModifierUtil.isAbstract(clazz) //
&& false == clazz.isEnum() //
&& false == clazz.isArray() //
&& false == clazz.isAnnotation() //

View File

@ -64,7 +64,7 @@ public class ConstructorUtil {
@SuppressWarnings("unchecked")
public static <T> Constructor<T>[] getConstructors(final Class<T> beanClass) throws SecurityException {
Assert.notNull(beanClass);
return (Constructor<T>[]) CONSTRUCTORS_CACHE.computeIfAbsent(beanClass, () -> getConstructorsDirectly(beanClass));
return (Constructor<T>[]) CONSTRUCTORS_CACHE.computeIfAbsent(beanClass, (key) -> getConstructorsDirectly(beanClass));
}
/**

View File

@ -116,7 +116,7 @@ public class FieldUtil {
*/
public static Field[] getFields(final Class<?> beanClass) throws SecurityException {
Assert.notNull(beanClass);
return FIELDS_CACHE.computeIfAbsent(beanClass, () -> getFieldsDirectly(beanClass, true));
return FIELDS_CACHE.computeIfAbsent(beanClass, (key) -> getFieldsDirectly(beanClass, true));
}

View File

@ -2,9 +2,10 @@ package cn.hutool.core.reflect;
import cn.hutool.core.bean.NullWrapperBean;
import cn.hutool.core.classloader.ClassLoaderUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.SetUtil;
import cn.hutool.core.collection.UniqueKeySet;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.exceptions.InvocationTargetRuntimeException;
import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Singleton;
@ -13,6 +14,7 @@ import cn.hutool.core.map.WeakConcurrentMap;
import cn.hutool.core.text.StrUtil;
import cn.hutool.core.util.ArrayUtil;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
@ -90,7 +92,7 @@ public class MethodUtil {
* @return 过滤后的方法列表
*/
public static Method[] getPublicMethods(final Class<?> clazz, final Method... excludeMethods) {
final HashSet<Method> excludeMethodSet = CollUtil.newHashSet(excludeMethods);
final HashSet<Method> excludeMethodSet = SetUtil.of(excludeMethods);
return getPublicMethods(clazz, method -> false == excludeMethodSet.contains(method));
}
@ -102,7 +104,7 @@ public class MethodUtil {
* @return 过滤后的方法数组
*/
public static Method[] getPublicMethods(final Class<?> clazz, final String... excludeMethodNames) {
final HashSet<String> excludeMethodNameSet = CollUtil.newHashSet(excludeMethodNames);
final HashSet<String> excludeMethodNameSet = SetUtil.of(excludeMethodNames);
return getPublicMethods(clazz, method -> false == excludeMethodNameSet.contains(method.getName()));
}
@ -318,7 +320,7 @@ public class MethodUtil {
public static Method[] getMethods(final Class<?> beanClass) throws SecurityException {
Assert.notNull(beanClass);
return METHODS_CACHE.computeIfAbsent(beanClass,
() -> getMethodsDirectly(beanClass, true, true));
(key) -> getMethodsDirectly(beanClass, true, true));
}
/**
@ -536,37 +538,39 @@ public class MethodUtil {
* @return 结果
* @throws UtilException 一些列异常的包装
*/
@SuppressWarnings("unchecked")
public static <T> T invoke(final Object obj, final Method method, final Object... args) throws UtilException {
ReflectUtil.setAccessible(method);
// 检查用户传入参数
// 1忽略多余的参数
// 2参数不够补齐默认值
// 3通过NullWrapperBean传递的参数,会直接赋值null
// 4传入参数为null但是目标参数类型为原始类型做转换
// 5传入参数类型不对应尝试转换类型
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 (false == parameterTypes[i].isAssignableFrom(args[i].getClass())) {
//对于类型不同的字段尝试转换转换失败则使用原对象类型
final Object targetValue = Convert.convert(parameterTypes[i], args[i]);
if (null != targetValue) {
actualArgs[i] = targetValue;
}
} else {
actualArgs[i] = args[i];
}
}
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 InvocationTargetRuntimeException 目标方法执行异常
* @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方法时尤其对象是代理对象需使用句柄方式执行
@ -574,11 +578,7 @@ public class MethodUtil {
return MethodHandleUtil.invokeSpecial(obj, method, args);
}
try {
return (T) method.invoke(ModifierUtil.isStatic(method) ? null : obj, actualArgs);
} catch (final Exception e) {
throw new UtilException(e);
}
return (T) method.invoke(ModifierUtil.isStatic(method) ? null : obj, actualArgs(method, args));
}
/**
@ -737,4 +737,44 @@ 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 (false == parameterTypes[i].isAssignableFrom(args[i].getClass())) {
//对于类型不同的字段尝试转换转换失败则使用原对象类型
final Object targetValue = Convert.convert(parameterTypes[i], args[i]);
if (null != targetValue) {
actualArgs[i] = targetValue;
}
} else {
actualArgs[i] = args[i];
}
}
}
return actualArgs;
}
}

View File

@ -192,6 +192,27 @@ public class ModifierUtil {
public static boolean isAbstract(final Member member) {
return hasModifier(member, ModifierType.ABSTRACT);
}
/**
* 是否抽象类
*
* @param clazz 构造字段或方法
* @return 是否抽象类
* @since 5.7.23
*/
public static boolean isAbstract(final Class<?> clazz) {
return hasModifier(clazz, ModifierType.ABSTRACT);
}
/**
* 是否抽象类
*
* @param clazz 构造字段或方法
* @return 是否抽象类
*/
public static boolean isInterface(final Class<?> clazz) {
return null != clazz && clazz.isInterface();
}
//-------------------------------------------------------------------------------------------------------- Private method start
/**

View File

@ -1,6 +1,6 @@
package cn.hutool.core.regex;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.SetUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.lang.Assert;
@ -45,7 +45,7 @@ public class ReUtil {
/**
* 正则中需要被转义的关键字
*/
public final static Set<Character> RE_KEYS = CollUtil.newHashSet('$', '(', ')', '*', '+', '.', '[', ']', '?', '\\', '^', '{', '}', '|');
public final static Set<Character> RE_KEYS = SetUtil.of('$', '(', ')', '*', '+', '.', '[', ']', '?', '\\', '^', '{', '}', '|');
/**
* 获得匹配的字符串获得正则中分组0的内容

View File

@ -168,7 +168,7 @@ public interface RegexPool {
* 十七位码车架号
* 车辆的唯一标示
*/
String CAR_VIN = "^[A-Za-z0-9]{17}$";
String CAR_VIN = "^[A-HJ-NPR-Z0-9]{8}[0-9X][A-HJ-NPR-Z0-9]{2}\\d{6}$";
/**
* 驾驶证 别名驾驶证档案编号行驶证编号
* eg:430101758218

View File

@ -779,6 +779,28 @@ public class CharSequenceUtil {
return false;
}
/**
* 给定字符串是否以任何一个字符串结尾忽略大小写<br>
* 给定字符串和数组为空都返回false
*
* @param str 给定字符串
* @param suffixes 需要检测的结尾字符串
* @return 给定字符串是否以任何一个字符串结尾
* @since 6.0.0
*/
public static boolean startWithAnyIgnoreCase(final CharSequence str, final CharSequence... suffixes) {
if (isEmpty(str) || ArrayUtil.isEmpty(suffixes)) {
return false;
}
for (final CharSequence suffix : suffixes) {
if (startWith(str, suffix, true)) {
return true;
}
}
return false;
}
// ------------------------------------------------------------------------ endWith
/**
@ -2706,7 +2728,7 @@ public class CharSequenceUtil {
* 如果想输出 {} 使用 \\转义 { 即可如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可<br>
* <br>
* 通常使用format("this is {} for {}", "a", "b") = this is a for b<br>
* 转义{} format("this is \\{} for {}", "a", "b") = this is \{} for a<br>
* 转义{} format("this is \\{} for {}", "a", "b") = this is {} for a<br>
* 转义\ format("this is \\\\{} for {}", "a", "b") = this is \a for b<br>
*
* @param template 文本模板被替换的部分用 {} 表示如果模板为null返回"null"

View File

@ -1,8 +1,8 @@
package cn.hutool.core.text.dfa;
import java.util.Set;
import cn.hutool.core.collection.SetUtil;
import cn.hutool.core.collection.CollUtil;
import java.util.Set;
/**
* 过滤词及一些简单处理
@ -11,7 +11,7 @@ import cn.hutool.core.collection.CollUtil;
*/
public class StopChar {
/** 不需要处理的词,如标点符号、空格等 */
public static final Set<Character> STOP_WORD = CollUtil.newHashSet(' ', '\'', '、', '。', //
public static final Set<Character> STOP_WORD = SetUtil.of(' ', '\'', '、', '。', //
'·', 'ˉ', 'ˇ', '々', '—', '', '‖', '…', '', '', '“', '”', '', '', '〈', '〉', '《', '》', '「', '」', '『', //
'』', '〖', '〗', '【', '】', '±', '', '', '×', '÷', '∧', '', '∑', '∏', '', '∩', '∈', '√', '⊥', '⊙', '∫', //
'∮', '≡', '≌', '≈', '∽', '∝', '≠', '≮', '≯', '≤', '≥', '∞', '', '∵', '∴', '∷', '♂', '♀', '°', '', '〃', //

View File

@ -1,6 +1,7 @@
package cn.hutool.core.text.dfa;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.SetUtil;
import cn.hutool.core.text.StrUtil;
import java.util.ArrayList;
@ -85,7 +86,7 @@ public class WordTree extends HashMap<Character, WordTree> {
* @return this
*/
public WordTree addWords(final String... words) {
for (final String word : CollUtil.newHashSet(words)) {
for (final String word : SetUtil.of(words)) {
addWord(word);
}
return this;

View File

@ -1,6 +1,7 @@
package cn.hutool.core.util;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.collection.UniqueKeySet;
import cn.hutool.core.comparator.CompareUtil;
import cn.hutool.core.exceptions.UtilException;
@ -1287,7 +1288,7 @@ public class ArrayUtil extends PrimitiveArrayUtil {
* @since 3.0.9
*/
public static <T> T[] toArray(final Iterator<T> iterator, final Class<T> componentType) {
return toArray(CollUtil.newArrayList(iterator), componentType);
return toArray(ListUtil.of(iterator), componentType);
}
/**

View File

@ -1,6 +1,6 @@
package cn.hutool.core.util;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.SetUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.text.StrUtil;
@ -15,7 +15,9 @@ import java.util.Set;
public class BooleanUtil {
/** 表示为真的字符串 */
private static final Set<String> TRUE_SET = CollUtil.newHashSet("true", "yes", "y", "t", "ok", "1", "on", "", "", "", "", "");
private static final Set<String> TRUE_SET = SetUtil.of("true", "yes", "y", "t", "ok", "1", "on", "", "", "", "", "");
/** 表示为假的字符串 */
private static final Set<String> FALSE_SET = SetUtil.of("false", "no", "n", "f", "0", "off", "", "", "", "", "×");
/**
* 取相反值
@ -86,6 +88,28 @@ public class BooleanUtil {
return false;
}
/**
* 转换字符串为boolean值<br>
* 如果为["true", "yes", "y", "t", "ok", "1", "on", "", "", "", "", ""]返回{@code true}<br>
* 如果为["false", "no", "n", "f", "0", "off", "", "", "", "", "×"]返回{@code false}<br>
* 其他情况返回{@code null}
*
* @param valueStr 字符串
* @return boolean值
* @since 5.8.1
*/
public static Boolean toBooleanObject(String valueStr) {
if (StrUtil.isNotBlank(valueStr)) {
valueStr = valueStr.trim().toLowerCase();
if(TRUE_SET.contains(valueStr)){
return true;
} else if(FALSE_SET.contains(valueStr)){
return false;
}
}
return null;
}
/**
* boolean值转为int
*

View File

@ -77,11 +77,24 @@ public class ByteUtil {
* @return short值
*/
public static short bytesToShort(final byte[] bytes, final ByteOrder byteOrder) {
return bytesToShort(bytes, 0, byteOrder);
}
/**
* byte数组转short<br>
* 自定义端序
*
* @param bytes byte数组长度必须大于2
* @param start 开始位置
* @param byteOrder 端序
* @return short值
*/
public static short bytesToShort(final byte[] bytes, final int start, final ByteOrder byteOrder) {
if (ByteOrder.LITTLE_ENDIAN == byteOrder) {
//小端模式数据的高字节保存在内存的高地址中而数据的低字节保存在内存的低地址中
return (short) (bytes[0] & 0xff | (bytes[1] & 0xff) << Byte.SIZE);
return (short) (bytes[start] & 0xff | (bytes[start + 1] & 0xff) << Byte.SIZE);
} else {
return (short) (bytes[1] & 0xff | (bytes[0] & 0xff) << Byte.SIZE);
return (short) (bytes[start + 1] & 0xff | (bytes[start] & 0xff) << Byte.SIZE);
}
}
@ -144,7 +157,7 @@ public class ByteUtil {
* 自定义端序
*
* @param bytes byte数组
* @param start 开始位置包含
* @param start 开始位置包含
* @param byteOrder 端序
* @return int值
* @since 5.7.21
@ -407,9 +420,9 @@ public class ByteUtil {
* @return bytes
*/
public static byte[] numberToBytes(final Number number, final ByteOrder byteOrder) {
if(number instanceof Byte){
if (number instanceof Byte) {
return new byte[]{number.byteValue()};
}else if (number instanceof Double) {
} else if (number instanceof Double) {
return doubleToBytes((Double) number, byteOrder);
} else if (number instanceof Long) {
return longToBytes((Long) number, byteOrder);

View File

@ -16,12 +16,12 @@ import java.util.Map;
import java.util.Objects;
/**
* 身份证相关工具类<br>
* see <a href="https://www.oschina.net/code/snippet_1611_2881">https://www.oschina.net/code/snippet_1611_2881</a>
* 身份证相关工具类参考标准GB 11643-1999<br>
* 标准描述见<a href="http://openstd.samr.gov.cn/bzgk/gb/newGbInfo?hcno=080D6FBF2BB468F9007657F26D60013E">http://openstd.samr.gov.cn/bzgk/gb/newGbInfo?hcno=080D6FBF2BB468F9007657F26D60013E</a>
*
* <p>
* 本工具并没有对行政区划代码做校验如有需求请参阅2018年10
* <a href="http://www.mca.gov.cn/article/sj/xzqh/2018/201804-12/20181011221630.html">http://www.mca.gov.cn/article/sj/xzqh/2018/201804-12/20181011221630.html</a>
* 本工具并没有对行政区划代码做校验如有需求请参阅2020年12
* <a href="http://www.mca.gov.cn/article/sj/xzqh/2020/20201201.html">http://www.mca.gov.cn/article/sj/xzqh/2020/20201201.html</a>
* </p>
*
* @author Looly
@ -118,7 +118,8 @@ public class IdcardUtil {
}
/**
* 将15位身份证号码转换为18位
* 将15位身份证号码转换为18位<br>
* 15位身份证号码遵循GB 11643-1989标准
*
* @param idCard 15位身份编码
* @return 18位身份编码
@ -422,17 +423,6 @@ public class IdcardUtil {
return sum % 11 == 0;
}
/**
* 根据身份编号获取生日只支持15或18位身份证号码
*
* @param idcard 身份编号
* @return 生日(yyyyMMdd)
* @see #getBirth(String)
*/
public static String getBirthByIdCard(final String idcard) {
return getBirth(idcard);
}
/**
* 根据身份编号获取生日只支持15或18位身份证号码
*
@ -458,8 +448,8 @@ public class IdcardUtil {
* @return 日期
*/
public static DateTime getBirthDate(final String idCard) {
final String birthByIdCard = getBirthByIdCard(idCard);
return null == birthByIdCard ? null : DateUtil.parse(birthByIdCard, DatePattern.PURE_DATE_FORMAT);
final String birth = getBirth(idCard);
return null == birth ? null : DateUtil.parse(birth, DatePattern.PURE_DATE_FORMAT);
}
/**
@ -468,8 +458,8 @@ public class IdcardUtil {
* @param idcard 身份编号
* @return 年龄
*/
public static int getAgeByIdCard(final String idcard) {
return getAgeByIdCard(idcard, DateUtil.date());
public static int getAge(final String idcard) {
return getAge(idcard, DateUtil.date());
}
/**
@ -479,9 +469,8 @@ public class IdcardUtil {
* @param dateToCompare 以此日期为界计算年龄
* @return 年龄
*/
public static int getAgeByIdCard(final String idcard, final Date dateToCompare) {
final String birth = getBirthByIdCard(idcard);
return DateUtil.age(DateUtil.parse(birth, "yyyyMMdd"), dateToCompare);
public static int getAge(final String idcard, final Date dateToCompare) {
return DateUtil.age(getBirthDate(idcard), dateToCompare);
}
/**
@ -490,7 +479,7 @@ public class IdcardUtil {
* @param idcard 身份编号
* @return 生日(yyyy)
*/
public static Short getYearByIdCard(String idcard) {
public static Short getBirthYear(String idcard) {
final int len = idcard.length();
if (len < CHINA_ID_MIN_LENGTH) {
return null;
@ -506,7 +495,7 @@ public class IdcardUtil {
* @param idcard 身份编号
* @return 生日(MM)
*/
public static Short getMonthByIdCard(String idcard) {
public static Short getBirthMonth(String idcard) {
final int len = idcard.length();
if (len < CHINA_ID_MIN_LENGTH) {
return null;
@ -522,7 +511,7 @@ public class IdcardUtil {
* @param idcard 身份编号
* @return 生日(dd)
*/
public static Short getDayByIdCard(String idcard) {
public static Short getBirthDay(String idcard) {
final int len = idcard.length();
if (len < CHINA_ID_MIN_LENGTH) {
return null;
@ -538,7 +527,7 @@ public class IdcardUtil {
* @param idcard 身份编号
* @return 性别(1 : 0 : )
*/
public static int getGenderByIdCard(String idcard) {
public static int getGender(String idcard) {
Assert.notBlank(idcard);
final int len = idcard.length();
if (len < CHINA_ID_MIN_LENGTH) {
@ -559,7 +548,7 @@ public class IdcardUtil {
* @return 省份编码
* @since 5.7.2
*/
public static String getProvinceCodeByIdCard(final String idcard) {
public static String getProvinceCode(final String idcard) {
final int len = idcard.length();
if (len == CHINA_ID_MIN_LENGTH || len == CHINA_ID_MAX_LENGTH) {
return idcard.substring(0, 2);
@ -573,8 +562,8 @@ public class IdcardUtil {
* @param idcard 身份编码
* @return 省份名称
*/
public static String getProvinceByIdCard(final String idcard) {
final String code = getProvinceCodeByIdCard(idcard);
public static String getProvince(final String idcard) {
final String code = getProvinceCode(idcard);
if (StrUtil.isNotBlank(code)) {
return CITY_CODES.get(code);
}
@ -588,7 +577,7 @@ public class IdcardUtil {
* @param idcard 身份编码
* @return 地市级编码
*/
public static String getCityCodeByIdCard(final String idcard) {
public static String getCityCode(final String idcard) {
final int len = idcard.length();
if (len == CHINA_ID_MIN_LENGTH || len == CHINA_ID_MAX_LENGTH) {
return idcard.substring(0, 4);
@ -604,7 +593,7 @@ public class IdcardUtil {
* @return 地市级编码
* @since 5.8.0
*/
public static String getDistrictCodeByIdCard(final String idcard) {
public static String getDistrictCode(final String idcard) {
final int len = idcard.length();
if (len == CHINA_ID_MIN_LENGTH || len == CHINA_ID_MAX_LENGTH) {
return idcard.substring(0, 6);
@ -637,6 +626,28 @@ public class IdcardUtil {
return new Idcard(idcard);
}
/**
* 港澳居民来往内地通行证俗称回乡证通行证号码组成规则<br>
* <ul>
* <li>通行证证件号码共11位第1位为字母H字头签发给香港居民M字头签发给澳门居民</li>
* <li>第2位至第11位为数字前8位数字为通行证持有人的终身号后2位数字表示换证次数首次发证为00此后依次递增</li>
* </ul>
* 示例H12345678M1234567801
*
* <p>
* 参考文档港澳居民来往内地通行证号码规则
* <a href="https://www.hmo.gov.cn/fwga_new/wldjnd/201711/t20171120_1333.html">https://www.hmo.gov.cn/fwga_new/wldjnd/201711/t20171120_1333.html</a>
* </p>
*/
public static boolean isValidHkMoHomeReturn(final String idCard) {
if (StrUtil.isEmpty(idCard)) {
return false;
}
// 规则 H/M + 8位或10位数字
// 样本 H1234567890
final String reg = "^[HhMm](\\d{8}|\\d{10})$";
return idCard.matches(reg);
}
// ----------------------------------------------------------------------------------- Private method start
/**
@ -723,11 +734,11 @@ public class IdcardUtil {
* @param idcard 身份证号码
*/
public Idcard(final String idcard) {
this.provinceCode = IdcardUtil.getProvinceCodeByIdCard(idcard);
this.cityCode = IdcardUtil.getCityCodeByIdCard(idcard);
this.provinceCode = IdcardUtil.getProvinceCode(idcard);
this.cityCode = IdcardUtil.getCityCode(idcard);
this.birthDate = IdcardUtil.getBirthDate(idcard);
this.gender = IdcardUtil.getGenderByIdCard(idcard);
this.age = IdcardUtil.getAgeByIdCard(idcard);
this.gender = IdcardUtil.getGender(idcard);
this.age = IdcardUtil.getAge(idcard);
}
/**

View File

@ -67,6 +67,7 @@ public class ObjUtil {
* <li>CharSequence</li>
* <li>Map</li>
* <li>Iterator</li>
* <li>Iterable</li>
* <li>Enumeration</li>
* <li>Array</li>
* </ul>
@ -89,8 +90,8 @@ public class ObjUtil {
}
int count;
if (obj instanceof Iterator) {
final Iterator<?> iter = (Iterator<?>) obj;
if (obj instanceof Iterator || obj instanceof Iterable) {
final Iterator<?> iter = (obj instanceof Iterator) ? (Iterator<?>) obj : ((Iterable<?>) obj).iterator();
count = 0;
while (iter.hasNext()) {
count++;
@ -107,7 +108,7 @@ public class ObjUtil {
}
return count;
}
if (obj.getClass().isArray() == true) {
if (obj.getClass().isArray()) {
return Array.getLength(obj);
}
return -1;
@ -121,6 +122,7 @@ public class ObjUtil {
* <li>Collection</li>
* <li>Map</li>
* <li>Iterator</li>
* <li>Iterable</li>
* <li>Enumeration</li>
* <li>Array</li>
* </ul>
@ -146,8 +148,8 @@ public class ObjUtil {
return ((Map<?, ?>) obj).containsValue(element);
}
if (obj instanceof Iterator) {
final Iterator<?> iter = (Iterator<?>) obj;
if (obj instanceof Iterator || obj instanceof Iterable) {
final Iterator<?> iter = obj instanceof Iterator ? (Iterator<?>) obj : ((Iterable<?>) obj).iterator();
while (iter.hasNext()) {
final Object o = iter.next();
if (equals(o, element)) {

View File

@ -445,7 +445,7 @@ public class RandomUtil {
*/
public static <T> List<T> randomEleList(final List<T> source, final int count) {
if (count >= source.size()) {
return ListUtil.toList(source);
return ListUtil.of(source);
}
final int[] randomList = ArrayUtil.sub(randomInts(source.size()), 0, count);
final List<T> result = new ArrayList<>();

View File

@ -30,7 +30,7 @@ public class ScriptUtil {
* @return {@link ScriptEngine} 实例
*/
public static ScriptEngine getScript(final String nameOrExtOrMime) {
return CACHE.computeIfAbsent(nameOrExtOrMime, () -> createScript(nameOrExtOrMime));
return CACHE.computeIfAbsent(nameOrExtOrMime, (key) -> createScript(nameOrExtOrMime));
}
/**

View File

@ -102,6 +102,6 @@ public class ServiceLoaderUtil {
* @since 5.4.2
*/
public static <T> List<T> loadList(final Class<T> clazz, final ClassLoader loader) {
return ListUtil.list(false, load(clazz, loader));
return ListUtil.of(false, load(clazz, loader));
}
}

View File

@ -1,7 +1,7 @@
package cn.hutool.core.util;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
@ -1109,7 +1109,7 @@ public class XmlUtil {
if (value instanceof List) {
((List<Object>) value).add(newValue);
} else {
result.put(childEle.getNodeName(), CollUtil.newArrayList(value, newValue));
result.put(childEle.getNodeName(), ListUtil.of(value, newValue));
}
} else {
result.put(childEle.getNodeName(), newValue);

View File

@ -1,17 +1,16 @@
package cn.hutool.core.bean;
import cn.hutool.core.lang.test.bean.ExamInfoDict;
import cn.hutool.core.lang.test.bean.UserInfoDict;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import cn.hutool.core.lang.test.bean.ExamInfoDict;
import cn.hutool.core.lang.test.bean.UserInfoDict;
/**
* {@link BeanPath} 单元测试
*
@ -87,14 +86,14 @@ public class BeanPathTest {
@Test
public void getTest() {
final BeanPath pattern = BeanPath.create("userInfo.examInfoDict[0].id");
final BeanPath pattern = BeanPath.of("userInfo.examInfoDict[0].id");
final Object result = pattern.get(tempMap);
Assert.assertEquals(1, result);
}
@Test
public void setTest() {
final BeanPath pattern = BeanPath.create("userInfo.examInfoDict[0].id");
final BeanPath pattern = BeanPath.of("userInfo.examInfoDict[0].id");
pattern.set(tempMap, 2);
final Object result = pattern.get(tempMap);
Assert.assertEquals(2, result);
@ -102,9 +101,28 @@ public class BeanPathTest {
@Test
public void getMapTest () {
final BeanPath pattern = BeanPath.create("userInfo[id, photoPath]");
@SuppressWarnings("unchecked") final Map<String, Object> result = (Map<String, Object>)pattern.get(tempMap);
final BeanPath pattern = BeanPath.of("userInfo[id, photoPath]");
@SuppressWarnings("unchecked")
final Map<String, Object> result = (Map<String, Object>)pattern.get(tempMap);
Assert.assertEquals(1, result.get("id"));
Assert.assertEquals("yx.mm.com", result.get("photoPath"));
}
@Test
public void getKeyWithDotTest () {
Map<String, Object> dataMap = new HashMap<>(16);
dataMap.put("aa", "value0");
dataMap.put("aa.bb.cc", "value111111");// key 是类名 格式 ' . '
final BeanPath pattern = BeanPath.of("'aa.bb.cc'");
Assert.assertEquals("value111111", pattern.get(dataMap));
}
@Test
public void compileTest(){
final BeanPath of = BeanPath.of("'abc.dd'.ee.ff'.'");
Assert.assertEquals("abc.dd", of.getPatternParts().get(0));
Assert.assertEquals("ee", of.getPatternParts().get(1));
Assert.assertEquals("ff.", of.getPatternParts().get(2));
}
}

View File

@ -3,14 +3,14 @@ package cn.hutool.core.bean;
import cn.hutool.core.annotation.Alias;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.bean.copier.ValueProvider;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.collection.SetUtil;
import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.StrUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.text.StrUtil;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
@ -116,7 +116,7 @@ public class BeanUtilTest {
// 错误的类型此处忽略
map.put("age", "aaaaaa");
final Person person = BeanUtil.toBeanIgnoreError(map, Person.class);
final Person person = BeanUtil.toBean(map, Person.class, CopyOptions.create().setIgnoreError(true));
Assert.assertEquals("Joe", person.getName());
// 错误的类型不copy这个字段使用对象创建的默认值
Assert.assertEquals(0, person.getAge());
@ -128,7 +128,7 @@ public class BeanUtilTest {
map.put("Name", "Joe");
map.put("aGe", 12);
final Person person = BeanUtil.toBeanIgnoreCase(map, Person.class, false);
final Person person = BeanUtil.toBean(map, Person.class, CopyOptions.create().setIgnoreCase(true));
Assert.assertEquals("Joe", person.getName());
Assert.assertEquals(12, person.getAge());
}
@ -191,6 +191,23 @@ public class BeanUtilTest {
Assert.assertFalse(map.containsKey("SUBNAME"));
}
@Test
public void beanToMapNullPropertiesTest() {
final SubPerson person = new SubPerson();
person.setAge(14);
person.setOpenid("11213232");
person.setName("测试A11");
person.setSubName("sub名字");
final Map<String, Object> map = BeanUtil.beanToMap(person, (String[])null);
Assert.assertEquals("测试A11", map.get("name"));
Assert.assertEquals(14, map.get("age"));
Assert.assertEquals("11213232", map.get("openid"));
// static属性应被忽略
Assert.assertFalse(map.containsKey("SUBNAME"));
}
@Test
public void beanToMapTest2() {
final SubPerson person = new SubPerson();
@ -285,7 +302,7 @@ public class BeanUtilTest {
@Test
public void getPropertyDescriptorsTest() {
final HashSet<Object> set = CollUtil.newHashSet();
final HashSet<Object> set = SetUtil.of();
final PropertyDescriptor[] propertyDescriptors = BeanUtil.getPropertyDescriptors(SubPerson.class);
for (final PropertyDescriptor propertyDescriptor : propertyDescriptors) {
set.add(propertyDescriptor.getName());
@ -326,7 +343,7 @@ public class BeanUtilTest {
student.setAge(125);
student.setNo(8848L);
final List<Student> studentList = ListUtil.of(student, student2);
final List<Student> studentList = ListUtil.view(student, student2);
for (int i=0;i<5000;i++){
new Thread(()->{
@ -550,6 +567,11 @@ public class BeanUtilTest {
Assert.assertNull(newFood.getCode());
}
@Test
public void copyNullTest() {
Assert.assertNull(BeanUtil.copyProperties(null, Food.class));
}
@Test
public void copyBeanPropertiesFilterTest() {
final Food info = new Food();
@ -633,7 +655,7 @@ public class BeanUtilTest {
student.setAge(125);
student.setNo(8848L);
final List<Student> studentList = ListUtil.of(student, student2);
final List<Student> studentList = ListUtil.view(student, student2);
final List<Person> people = BeanUtil.copyToList(studentList, Person.class);
Assert.assertEquals(studentList.size(), people.size());
@ -687,7 +709,7 @@ public class BeanUtilTest {
testPojo.setTestPojo2List(new TestPojo2[]{testPojo2, testPojo3});
final BeanPath beanPath = BeanPath.create("testPojo2List.age");
final BeanPath beanPath = BeanPath.of("testPojo2List.age");
final Object o = beanPath.get(testPojo);
Assert.assertEquals(Integer.valueOf(2), ArrayUtil.get(o, 0));
@ -759,7 +781,7 @@ public class BeanUtilTest {
@Test
public void issueI41WKPTest(){
final Test1 t1 = new Test1().setStrList(ListUtil.toList("list"));
final Test1 t1 = new Test1().setStrList(ListUtil.of("list"));
final Test2 t2_hu = new Test2();
BeanUtil.copyProperties(t1, t2_hu, CopyOptions.create().setIgnoreError(true));
Assert.assertNull(t2_hu.getStrList());

View File

@ -35,22 +35,22 @@ public class CollUtilTest {
@Test
public void testPredicateContains() {
final ArrayList<String> list = CollUtil.newArrayList("bbbbb", "aaaaa", "ccccc");
final ArrayList<String> list = ListUtil.of("bbbbb", "aaaaa", "ccccc");
Assert.assertTrue(CollUtil.contains(list, s -> s.startsWith("a")));
Assert.assertFalse(CollUtil.contains(list, s -> s.startsWith("d")));
}
@Test
public void testRemoveWithAddIf() {
ArrayList<Integer> list = CollUtil.newArrayList(1, 2, 3);
final ArrayList<Integer> exceptRemovedList = CollUtil.newArrayList(2, 3);
final ArrayList<Integer> exceptResultList = CollUtil.newArrayList(1);
ArrayList<Integer> list = ListUtil.of(1, 2, 3);
final ArrayList<Integer> exceptRemovedList = ListUtil.of(2, 3);
final ArrayList<Integer> exceptResultList = ListUtil.of(1);
List<Integer> resultList = CollUtil.removeWithAddIf(list, ele -> 1 == ele);
Assert.assertEquals(list, exceptRemovedList);
Assert.assertEquals(resultList, exceptResultList);
list = CollUtil.newArrayList(1, 2, 3);
list = ListUtil.of(1, 2, 3);
resultList = new ArrayList<>();
CollUtil.removeWithAddIf(list, resultList, ele -> 1 == ele);
Assert.assertEquals(list, exceptRemovedList);
@ -59,27 +59,27 @@ public class CollUtilTest {
@Test
public void testPadLeft() {
List<String> srcList = CollUtil.newArrayList();
List<String> answerList = CollUtil.newArrayList("a", "b");
List<String> srcList = ListUtil.of();
List<String> answerList = ListUtil.of("a", "b");
CollUtil.padLeft(srcList, 1, "b");
CollUtil.padLeft(srcList, 2, "a");
Assert.assertEquals(srcList, answerList);
srcList = CollUtil.newArrayList("a", "b");
answerList = CollUtil.newArrayList("a", "b");
srcList = ListUtil.of("a", "b");
answerList = ListUtil.of("a", "b");
CollUtil.padLeft(srcList, 2, "a");
Assert.assertEquals(srcList, answerList);
srcList = CollUtil.newArrayList("c");
answerList = CollUtil.newArrayList("a", "a", "c");
srcList = ListUtil.of("c");
answerList = ListUtil.of("a", "a", "c");
CollUtil.padLeft(srcList, 3, "a");
Assert.assertEquals(srcList, answerList);
}
@Test
public void testPadRight() {
final List<String> srcList = CollUtil.newArrayList("a");
final List<String> answerList = CollUtil.newArrayList("a", "b", "b", "b", "b");
final List<String> srcList = ListUtil.of("a");
final List<String> answerList = ListUtil.of("a", "b", "b", "b", "b");
CollUtil.padRight(srcList, 5, "b");
Assert.assertEquals(srcList, answerList);
}
@ -91,7 +91,7 @@ public class CollUtilTest {
@Test
public void newHashSetTest() {
final Set<String> set = CollUtil.newHashSet((String[]) null);
final Set<String> set = SetUtil.of((String[]) null);
Assert.assertNotNull(set);
}
@ -114,8 +114,8 @@ public class CollUtilTest {
@Test
public void unionTest() {
final ArrayList<String> list1 = CollUtil.newArrayList("a", "b", "b", "c", "d", "x");
final ArrayList<String> list2 = CollUtil.newArrayList("a", "b", "b", "b", "c", "d");
final ArrayList<String> list1 = ListUtil.of("a", "b", "b", "c", "d", "x");
final ArrayList<String> list2 = ListUtil.of("a", "b", "b", "b", "c", "d");
final Collection<String> union = CollUtil.union(list1, list2);
@ -124,8 +124,8 @@ public class CollUtilTest {
@Test
public void intersectionTest() {
final ArrayList<String> list1 = CollUtil.newArrayList("a", "b", "b", "c", "d", "x");
final ArrayList<String> list2 = CollUtil.newArrayList("a", "b", "b", "b", "c", "d");
final ArrayList<String> list1 = ListUtil.of("a", "b", "b", "c", "d", "x");
final ArrayList<String> list2 = ListUtil.of("a", "b", "b", "b", "c", "d");
final Collection<String> intersection = CollUtil.intersection(list1, list2);
Assert.assertEquals(2, CollUtil.count(intersection, "b"::equals));
@ -133,12 +133,12 @@ public class CollUtilTest {
@Test
public void intersectionDistinctTest() {
final ArrayList<String> list1 = CollUtil.newArrayList("a", "b", "b", "c", "d", "x");
final ArrayList<String> list2 = CollUtil.newArrayList("a", "b", "b", "b", "c", "d");
final ArrayList<String> list3 = CollUtil.newArrayList();
final ArrayList<String> list1 = ListUtil.of("a", "b", "b", "c", "d", "x");
final ArrayList<String> list2 = ListUtil.of("a", "b", "b", "b", "c", "d");
final ArrayList<String> list3 = ListUtil.of();
final Collection<String> intersectionDistinct = CollUtil.intersectionDistinct(list1, list2);
Assert.assertEquals(CollUtil.newLinkedHashSet("a", "b", "c", "d"), intersectionDistinct);
Assert.assertEquals(SetUtil.ofLinked("a", "b", "c", "d"), intersectionDistinct);
final Collection<String> intersectionDistinct2 = CollUtil.intersectionDistinct(list1, list2, list3);
Assert.assertTrue(intersectionDistinct2.isEmpty());
@ -146,8 +146,8 @@ public class CollUtilTest {
@Test
public void disjunctionTest() {
final ArrayList<String> list1 = CollUtil.newArrayList("a", "b", "b", "c", "d", "x");
final ArrayList<String> list2 = CollUtil.newArrayList("a", "b", "b", "b", "c", "d", "x2");
final ArrayList<String> list1 = ListUtil.of("a", "b", "b", "c", "d", "x");
final ArrayList<String> list2 = ListUtil.of("a", "b", "b", "b", "c", "d", "x2");
final Collection<String> disjunction = CollUtil.disjunction(list1, list2);
Assert.assertTrue(disjunction.contains("b"));
@ -163,8 +163,8 @@ public class CollUtilTest {
@Test
public void disjunctionTest2() {
// 任意一个集合为空差集为另一个集合
final ArrayList<String> list1 = CollUtil.newArrayList();
final ArrayList<String> list2 = CollUtil.newArrayList("a", "b", "b", "b", "c", "d", "x2");
final ArrayList<String> list1 = ListUtil.of();
final ArrayList<String> list2 = ListUtil.of("a", "b", "b", "b", "c", "d", "x2");
final Collection<String> disjunction = CollUtil.disjunction(list1, list2);
Assert.assertEquals(list2, disjunction);
@ -175,8 +175,8 @@ public class CollUtilTest {
@Test
public void disjunctionTest3() {
// 无交集下返回共同的元素
final ArrayList<String> list1 = CollUtil.newArrayList("1", "2", "3");
final ArrayList<String> list2 = CollUtil.newArrayList("a", "b", "c");
final ArrayList<String> list1 = ListUtil.of("1", "2", "3");
final ArrayList<String> list2 = ListUtil.of("a", "b", "c");
final Collection<String> disjunction = CollUtil.disjunction(list1, list2);
Assert.assertTrue(disjunction.contains("1"));
@ -196,8 +196,8 @@ public class CollUtilTest {
@Test
public void subtractTest() {
final List<String> list1 = CollUtil.newArrayList("a", "b", "b", "c", "d", "x");
final List<String> list2 = CollUtil.newArrayList("a", "b", "b", "b", "c", "d", "x2");
final List<String> list1 = ListUtil.of("a", "b", "b", "c", "d", "x");
final List<String> list2 = ListUtil.of("a", "b", "b", "b", "c", "d", "x2");
final Collection<String> subtract = CollUtil.subtract(list1, list2);
Assert.assertEquals(1, subtract.size());
Assert.assertEquals("x", subtract.iterator().next());
@ -236,7 +236,7 @@ public class CollUtilTest {
map2.put("c", "值3");
// ----------------------------------------------------------------------------------------
final ArrayList<HashMap<String, String>> list = CollUtil.newArrayList(map1, map2);
final ArrayList<HashMap<String, String>> list = ListUtil.of(map1, map2);
final Map<String, List<String>> map = CollUtil.toListMap(list);
Assert.assertEquals("值1", map.get("a").get(0));
Assert.assertEquals("值2", map.get("a").get(1));
@ -251,7 +251,7 @@ public class CollUtilTest {
public void getFieldValuesTest() {
final Dict v1 = Dict.create().set("id", 12).set("name", "张三").set("age", 23);
final Dict v2 = Dict.create().set("age", 13).set("id", 15).set("name", "李四");
final ArrayList<Dict> list = CollUtil.newArrayList(v1, v2);
final ArrayList<Dict> list = ListUtil.of(v1, v2);
final List<Object> fieldValues = CollUtil.getFieldValues(list, "name");
Assert.assertEquals("张三", fieldValues.get(0));
@ -260,7 +260,7 @@ public class CollUtilTest {
@Test
public void splitTest() {
final ArrayList<Integer> list = CollUtil.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9);
final ArrayList<Integer> list = ListUtil.of(1, 2, 3, 4, 5, 6, 7, 8, 9);
final List<List<Integer>> split = CollUtil.split(list, 3);
Assert.assertEquals(3, split.size());
Assert.assertEquals(3, split.get(0).size());
@ -285,35 +285,35 @@ public class CollUtilTest {
@Test
public void filterTest() {
final ArrayList<String> list = CollUtil.newArrayList("a", "b", "c");
final ArrayList<String> list = ListUtil.of("a", "b", "c");
final Collection<String> filtered = CollUtil.edit(list, t -> t + 1);
Assert.assertEquals(CollUtil.newArrayList("a1", "b1", "c1"), filtered);
Assert.assertEquals(ListUtil.of("a1", "b1", "c1"), filtered);
}
@Test
public void filterTest2() {
final ArrayList<String> list = CollUtil.newArrayList("a", "b", "c");
final ArrayList<String> list = ListUtil.of("a", "b", "c");
final ArrayList<String> filtered = CollUtil.filter(list, t -> false == "a".equals(t));
// 原地过滤
Assert.assertSame(list, filtered);
Assert.assertEquals(CollUtil.newArrayList("b", "c"), filtered);
Assert.assertEquals(ListUtil.of("b", "c"), filtered);
}
@Test
public void filterSetTest() {
final Set<String> set = CollUtil.newLinkedHashSet("a", "b", "", " ", "c");
final Set<String> set = SetUtil.ofLinked("a", "b", "", " ", "c");
final Set<String> filtered = CollUtil.filter(set, StrUtil::isNotBlank);
Assert.assertEquals(CollUtil.newLinkedHashSet("a", "b", "c"), filtered);
Assert.assertEquals(SetUtil.ofLinked("a", "b", "c"), filtered);
}
@Test
public void filterRemoveTest() {
final ArrayList<String> list = CollUtil.newArrayList("a", "b", "c");
final ArrayList<String> list = ListUtil.of("a", "b", "c");
final List<String> removed = new ArrayList<>();
final ArrayList<String> filtered = CollUtil.filter(list, t -> {
@ -329,45 +329,45 @@ public class CollUtilTest {
// 原地过滤
Assert.assertSame(list, filtered);
Assert.assertEquals(CollUtil.newArrayList("b", "c"), filtered);
Assert.assertEquals(ListUtil.of("b", "c"), filtered);
}
@Test
public void removeNullTest() {
final ArrayList<String> list = CollUtil.newArrayList("a", "b", "c", null, "", " ");
final ArrayList<String> list = ListUtil.of("a", "b", "c", null, "", " ");
final ArrayList<String> filtered = CollUtil.removeNull(list);
// 原地过滤
Assert.assertSame(list, filtered);
Assert.assertEquals(CollUtil.newArrayList("a", "b", "c", "", " "), filtered);
Assert.assertEquals(ListUtil.of("a", "b", "c", "", " "), filtered);
}
@Test
public void removeEmptyTest() {
final ArrayList<String> list = CollUtil.newArrayList("a", "b", "c", null, "", " ");
final ArrayList<String> list = ListUtil.of("a", "b", "c", null, "", " ");
final ArrayList<String> filtered = CollUtil.removeEmpty(list);
// 原地过滤
Assert.assertSame(list, filtered);
Assert.assertEquals(CollUtil.newArrayList("a", "b", "c", " "), filtered);
Assert.assertEquals(ListUtil.of("a", "b", "c", " "), filtered);
}
@Test
public void removeBlankTest() {
final ArrayList<String> list = CollUtil.newArrayList("a", "b", "c", null, "", " ");
final ArrayList<String> list = ListUtil.of("a", "b", "c", null, "", " ");
final ArrayList<String> filtered = CollUtil.removeBlank(list);
// 原地过滤
Assert.assertSame(list, filtered);
Assert.assertEquals(CollUtil.newArrayList("a", "b", "c"), filtered);
Assert.assertEquals(ListUtil.of("a", "b", "c"), filtered);
}
@Test
public void groupTest() {
final List<String> list = CollUtil.newArrayList("1", "2", "3", "4", "5", "6");
final List<String> list = ListUtil.of("1", "2", "3", "4", "5", "6");
final List<List<String>> group = CollUtil.group(list, null);
Assert.assertTrue(group.size() > 0);
@ -375,13 +375,13 @@ public class CollUtilTest {
// 按照奇数偶数分类
return Integer.parseInt(t) % 2;
});
Assert.assertEquals(CollUtil.newArrayList("2", "4", "6"), group2.get(0));
Assert.assertEquals(CollUtil.newArrayList("1", "3", "5"), group2.get(1));
Assert.assertEquals(ListUtil.of("2", "4", "6"), group2.get(0));
Assert.assertEquals(ListUtil.of("1", "3", "5"), group2.get(1));
}
@Test
public void groupByFieldTest() {
final List<TestBean> list = CollUtil.newArrayList(new TestBean("张三", 12), new TestBean("李四", 13), new TestBean("王五", 12));
final List<TestBean> list = ListUtil.of(new TestBean("张三", 12), new TestBean("李四", 13), new TestBean("王五", 12));
final List<List<TestBean>> groupByField = CollUtil.groupByField(list, "age");
Assert.assertEquals("张三", groupByField.get(0).get(0).getName());
Assert.assertEquals("王五", groupByField.get(0).get(1).getName());
@ -391,7 +391,7 @@ public class CollUtilTest {
@Test
public void sortByPropertyTest() {
final List<TestBean> list = CollUtil.newArrayList(
final List<TestBean> list = ListUtil.of(
new TestBean("张三", 12, DateUtil.parse("2018-05-01")), //
new TestBean("李四", 13, DateUtil.parse("2018-03-01")), //
new TestBean("王五", 12, DateUtil.parse("2018-04-01"))//
@ -405,7 +405,7 @@ public class CollUtilTest {
@Test
public void sortByPropertyTest2() {
final List<TestBean> list = CollUtil.newArrayList(
final List<TestBean> list = ListUtil.of(
new TestBean("张三", 0, DateUtil.parse("2018-05-01")), //
new TestBean("李四", -12, DateUtil.parse("2018-03-01")), //
new TestBean("王五", 23, DateUtil.parse("2018-04-01"))//
@ -419,7 +419,7 @@ public class CollUtilTest {
@Test
public void fieldValueMapTest() {
final List<TestBean> list = CollUtil.newArrayList(new TestBean("张三", 12, DateUtil.parse("2018-05-01")), //
final List<TestBean> list = ListUtil.of(new TestBean("张三", 12, DateUtil.parse("2018-05-01")), //
new TestBean("李四", 13, DateUtil.parse("2018-03-01")), //
new TestBean("王五", 12, DateUtil.parse("2018-04-01"))//
);
@ -432,7 +432,7 @@ public class CollUtilTest {
@Test
public void fieldValueAsMapTest() {
final List<TestBean> list = CollUtil.newArrayList(new TestBean("张三", 12, DateUtil.parse("2018-05-01")), //
final List<TestBean> list = ListUtil.of(new TestBean("张三", 12, DateUtil.parse("2018-05-01")), //
new TestBean("李四", 13, DateUtil.parse("2018-03-01")), //
new TestBean("王五", 14, DateUtil.parse("2018-04-01"))//
);
@ -470,8 +470,8 @@ public class CollUtilTest {
@Test
public void listTest() {
final List<Object> list1 = CollUtil.list(false);
final List<Object> list2 = CollUtil.list(true);
final List<Object> list1 = ListUtil.of(false);
final List<Object> list2 = ListUtil.of(true);
Assert.assertTrue(list1 instanceof ArrayList);
Assert.assertTrue(list2 instanceof LinkedList);
@ -479,8 +479,8 @@ public class CollUtilTest {
@Test
public void listTest2() {
final List<String> list1 = CollUtil.list(false, "a", "b", "c");
final List<String> list2 = CollUtil.list(true, "a", "b", "c");
final List<String> list1 = ListUtil.of( "a", "b", "c");
final List<String> list2 = ListUtil.ofLinked( "a", "b", "c");
Assert.assertEquals("[a, b, c]", list1.toString());
Assert.assertEquals("[a, b, c]", list2.toString());
}
@ -492,15 +492,15 @@ public class CollUtilTest {
set.add("b");
set.add("c");
final List<String> list1 = CollUtil.list(false, set);
final List<String> list2 = CollUtil.list(true, set);
final List<String> list1 = ListUtil.of(false, set);
final List<String> list2 = ListUtil.of(true, set);
Assert.assertEquals("[a, b, c]", list1.toString());
Assert.assertEquals("[a, b, c]", list2.toString());
}
@Test
public void getTest() {
final HashSet<String> set = CollUtil.set(true, "A", "B", "C", "D");
final HashSet<String> set = SetUtil.ofLinked("A", "B", "C", "D");
String str = CollUtil.get(set, 2);
Assert.assertEquals("C", str);
@ -701,43 +701,43 @@ public class CollUtilTest {
@Test
public void sortPageAllTest() {
final List<Integer> list = CollUtil.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9);
final List<Integer> list = ListUtil.of(1, 2, 3, 4, 5, 6, 7, 8, 9);
final List<Integer> sortPageAll = CollUtil.sortPageAll(1, 5, Comparator.reverseOrder(), list);
Assert.assertEquals(CollUtil.newArrayList(4, 3, 2, 1), sortPageAll);
Assert.assertEquals(ListUtil.of(4, 3, 2, 1), sortPageAll);
}
@Test
public void containsAnyTest() {
final ArrayList<Integer> list1 = CollUtil.newArrayList(1, 2, 3, 4, 5);
final ArrayList<Integer> list2 = CollUtil.newArrayList(5, 3, 1, 9, 11);
final ArrayList<Integer> list1 = ListUtil.of(1, 2, 3, 4, 5);
final ArrayList<Integer> list2 = ListUtil.of(5, 3, 1, 9, 11);
Assert.assertTrue(CollUtil.containsAny(list1, list2));
}
@Test
public void containsAllTest() {
final ArrayList<Integer> list1 = CollUtil.newArrayList(1, 2, 3, 4, 5);
final ArrayList<Integer> list2 = CollUtil.newArrayList(5, 3, 1);
final ArrayList<Integer> list1 = ListUtil.of(1, 2, 3, 4, 5);
final ArrayList<Integer> list2 = ListUtil.of(5, 3, 1);
Assert.assertTrue(CollUtil.containsAll(list1, list2));
final ArrayList<Integer> list3 = CollUtil.newArrayList(1);
final ArrayList<Integer> list4 = CollUtil.newArrayList();
final ArrayList<Integer> list3 = ListUtil.of(1);
final ArrayList<Integer> list4 = ListUtil.of();
Assert.assertTrue(CollUtil.containsAll(list3, list4));
}
@Test
public void getLastTest() {
// 测试空数组返回null而不是报错
final List<String> test = CollUtil.newArrayList();
final List<String> test = ListUtil.of();
final String last = CollUtil.getLast(test);
Assert.assertNull(last);
}
@Test
public void zipTest() {
final Collection<String> keys = CollUtil.newArrayList("a", "b", "c", "d");
final Collection<Integer> values = CollUtil.newArrayList(1, 2, 3, 4);
final Collection<String> keys = ListUtil.of("a", "b", "c", "d");
final Collection<Integer> values = ListUtil.of(1, 2, 3, 4);
final Map<String, Integer> map = CollUtil.zip(keys, values);
@ -751,7 +751,7 @@ public class CollUtilTest {
@Test
public void toMapTest() {
final Collection<String> keys = CollUtil.newArrayList("a", "b", "c", "d");
final Collection<String> keys = ListUtil.of("a", "b", "c", "d");
final Map<String, String> map = CollUtil.toMap(keys, new HashMap<>(), (value) -> "key" + value);
Assert.assertEquals("a", map.get("keya"));
Assert.assertEquals("b", map.get("keyb"));
@ -778,7 +778,7 @@ public class CollUtilTest {
@Test
public void countMapTest() {
final ArrayList<String> list = CollUtil.newArrayList("a", "b", "c", "c", "a", "b", "d");
final ArrayList<String> list = ListUtil.of("a", "b", "c", "c", "a", "b", "d");
final Map<String, Integer> countMap = CollUtil.countMap(list);
Assert.assertEquals(Integer.valueOf(2), countMap.get("a"));
@ -789,7 +789,7 @@ public class CollUtilTest {
@Test
public void indexOfTest() {
final ArrayList<String> list = CollUtil.newArrayList("a", "b", "c", "c", "a", "b", "d");
final ArrayList<String> list = ListUtil.of("a", "b", "c", "c", "a", "b", "d");
final int i = CollUtil.indexOf(list, (str) -> str.charAt(0) == 'c');
Assert.assertEquals(2, i);
}
@ -797,14 +797,14 @@ public class CollUtilTest {
@Test
public void lastIndexOfTest() {
// List有优化
final ArrayList<String> list = CollUtil.newArrayList("a", "b", "c", "c", "a", "b", "d");
final ArrayList<String> list = ListUtil.of("a", "b", "c", "c", "a", "b", "d");
final int i = CollUtil.lastIndexOf(list, (str) -> str.charAt(0) == 'c');
Assert.assertEquals(3, i);
}
@Test
public void lastIndexOfSetTest() {
final Set<String> list = CollUtil.set(true, "a", "b", "c", "c", "a", "b", "d");
final Set<String> list = SetUtil.ofLinked("a", "b", "c", "c", "a", "b", "d");
// 去重后c排第三
final int i = CollUtil.lastIndexOf(list, (str) -> str.charAt(0) == 'c');
Assert.assertEquals(2, i);
@ -812,7 +812,7 @@ public class CollUtilTest {
@Test
public void pageTest() {
final List<Dict> objects = CollUtil.newArrayList();
final List<Dict> objects = ListUtil.of();
for (int i = 0; i < 10; i++) {
objects.add(Dict.create().set("name", "姓名:" + i));
}
@ -832,7 +832,7 @@ public class CollUtilTest {
@Test
public void sortComparableTest() {
final List<String> of = ListUtil.toList("a", "c", "b");
final List<String> of = ListUtil.of("a", "c", "b");
final List<String> sort = CollUtil.sort(of, new ComparableComparator<>());
Assert.assertEquals("a,b,c", CollUtil.join(sort, ","));
}
@ -880,8 +880,8 @@ public class CollUtilTest {
@Test
public void distinctTest(){
final ArrayList<Integer> distinct = CollUtil.distinct(ListUtil.of(5, 3, 10, 9, 0, 5, 10, 9));
Assert.assertEquals(ListUtil.of(5, 3, 10, 9, 0), distinct);
final ArrayList<Integer> distinct = CollUtil.distinct(ListUtil.view(5, 3, 10, 9, 0, 5, 10, 9));
Assert.assertEquals(ListUtil.view(5, 3, 10, 9, 0), distinct);
}
@Test

View File

@ -17,20 +17,20 @@ import java.util.Map;
/**
* {@link IterUtil} 单元测试
* @author looly
*
* @author looly
*/
public class IterUtilTest {
@Test
public void getFirstNonNullTest(){
final ArrayList<String> strings = CollUtil.newArrayList(null, null, "123", "456", null);
public void getFirstNonNullTest() {
final ArrayList<String> strings = ListUtil.of(null, null, "123", "456", null);
Assert.assertEquals("123", IterUtil.getFirstNoneNull(strings));
}
@Test
public void fieldValueMapTest() {
final ArrayList<Car> carList = CollUtil.newArrayList(new Car("123", "大众"), new Car("345", "奔驰"), new Car("567", "路虎"));
final ArrayList<Car> carList = ListUtil.of(new Car("123", "大众"), new Car("345", "奔驰"), new Car("567", "路虎"));
final Map<String, Car> carNameMap = IterUtil.fieldValueMap(carList.iterator(), "carNumber");
Assert.assertEquals("大众", carNameMap.get("123").getCarName());
@ -40,30 +40,30 @@ public class IterUtilTest {
@Test
public void joinTest() {
final ArrayList<String> list = CollUtil.newArrayList("1", "2", "3", "4");
final ArrayList<String> list = ListUtil.of("1", "2", "3", "4");
final String join = IterUtil.join(list.iterator(), ":");
Assert.assertEquals("1:2:3:4", join);
final ArrayList<Integer> list1 = CollUtil.newArrayList(1, 2, 3, 4);
final ArrayList<Integer> list1 = ListUtil.of(1, 2, 3, 4);
final String join1 = IterUtil.join(list1.iterator(), ":");
Assert.assertEquals("1:2:3:4", join1);
// 包装每个节点
final ArrayList<String> list2 = CollUtil.newArrayList("1", "2", "3", "4");
final ArrayList<String> list2 = ListUtil.of("1", "2", "3", "4");
final String join2 = IterUtil.join(list2.iterator(), ":", "\"", "\"");
Assert.assertEquals("\"1\":\"2\":\"3\":\"4\"", join2);
}
@Test
public void joinWithFuncTest() {
final ArrayList<String> list = CollUtil.newArrayList("1", "2", "3", "4");
final ArrayList<String> list = ListUtil.of("1", "2", "3", "4");
final String join = IterUtil.join(list.iterator(), ":", String::valueOf);
Assert.assertEquals("1:2:3:4", join);
}
@Test
public void joinWithNullTest() {
final ArrayList<String> list = CollUtil.newArrayList("1", null, "3", "4");
final ArrayList<String> list = ListUtil.of("1", null, "3", "4");
final String join = IterUtil.join(list.iterator(), ":", String::valueOf);
Assert.assertEquals("1:null:3:4", join);
}
@ -94,10 +94,10 @@ public class IterUtilTest {
}
@Test
public void getElementTypeTest(){
public void getElementTypeTest() {
final List<Integer> integers = Arrays.asList(null, 1);
final Class<?> elementType = IterUtil.getElementType(integers);
Assert.assertEquals(Integer.class,elementType);
Assert.assertEquals(Integer.class, elementType);
}
@Data
@ -108,9 +108,9 @@ public class IterUtilTest {
}
@Test
public void filterTest(){
final List<String> obj2 = ListUtil.toList("3");
final List<String> obj = ListUtil.toList("1", "3");
public void filterTest() {
final List<String> obj2 = ListUtil.of("3");
final List<String> obj = ListUtil.of("1", "3");
IterUtil.filter(obj.iterator(), obj2::contains);
@ -119,9 +119,9 @@ public class IterUtilTest {
}
@Test
public void filteredTest(){
final List<String> obj2 = ListUtil.toList("3");
final List<String> obj = ListUtil.toList("1", "3");
public void filteredTest() {
final List<String> obj2 = ListUtil.of("3");
final List<String> obj = ListUtil.of("1", "3");
final FilterIter<String> filtered = IterUtil.filtered(obj.iterator(), obj2::contains);
@ -130,9 +130,9 @@ public class IterUtilTest {
}
@Test
public void filterToListTest(){
final List<String> obj2 = ListUtil.toList("3");
final List<String> obj = ListUtil.toList("1", "3");
public void filterToListTest() {
final List<String> obj2 = ListUtil.of("3");
final List<String> obj = ListUtil.of("1", "3");
final List<String> filtered = IterUtil.filterToList(obj.iterator(), obj2::contains);
@ -142,7 +142,7 @@ public class IterUtilTest {
@Test
public void getTest() {
final HashSet<String> set = CollUtil.set(true, "A", "B", "C", "D");
final HashSet<String> set = SetUtil.ofLinked("A", "B", "C", "D");
final String str = IterUtil.get(set.iterator(), 2);
Assert.assertEquals("C", str);
}

View File

@ -87,7 +87,7 @@ public class ListUtilTest {
@Test
public void editTest() {
final List<String> a = ListUtil.toLinkedList("1", "2", "3");
final List<String> a = ListUtil.ofLinked("1", "2", "3");
final List<String> filter = (List<String>) CollUtil.edit(a, str -> "edit" + str);
Assert.assertEquals("edit1", filter.get(0));
Assert.assertEquals("edit2", filter.get(1));
@ -96,16 +96,16 @@ public class ListUtilTest {
@Test
public void indexOfAll() {
final List<String> a = ListUtil.toLinkedList("1", "2", "3", "4", "3", "2", "1");
final int[] indexArray = ListUtil.indexOfAll(a, "2"::equals);
final List<String> a = ListUtil.ofLinked("1", "2", "3", "4", "3", "2", "1");
final int[] indexArray = CollUtil.indexOfAll(a, "2"::equals);
Assert.assertArrayEquals(new int[]{1,5}, indexArray);
final int[] indexArray2 = ListUtil.indexOfAll(a, "1"::equals);
final int[] indexArray2 = CollUtil.indexOfAll(a, "1"::equals);
Assert.assertArrayEquals(new int[]{0,6}, indexArray2);
}
@Test
public void pageTest() {
final List<Integer> a = ListUtil.toLinkedList(1, 2, 3,4,5);
final List<Integer> a = ListUtil.ofLinked(1, 2, 3,4,5);
PageUtil.setFirstPageNo(1);
final int[] a_1 = ListUtil.page(1,2,a).stream().mapToInt(Integer::valueOf).toArray();
@ -174,7 +174,7 @@ public class ListUtilTest {
@Test
public void subTest() {
final List<Integer> of = ListUtil.of(1, 2, 3, 4);
final List<Integer> of = ListUtil.view(1, 2, 3, 4);
final List<Integer> sub = ListUtil.sub(of, 2, 4);
sub.remove(0);
@ -192,7 +192,7 @@ public class ListUtilTest {
private String name;
}
final List<TestBean> beanList = ListUtil.toList(
final List<TestBean> beanList = ListUtil.of(
new TestBean(2, "test2"),
new TestBean(1, "test1"),
new TestBean(5, "test5"),

View File

@ -22,7 +22,7 @@ public class PartitionIterTest {
@Test
public void iterMaxTest() {
final List<Integer> list = ListUtil.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 0, 12, 45, 12);
final List<Integer> list = ListUtil.view(1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 0, 12, 45, 12);
final PartitionIter<Integer> iter = new PartitionIter<>(list.iterator(), 3);
int max = 0;
for (final List<Integer> lines : iter) {

View File

@ -19,10 +19,10 @@ public class CompareUtilTest {
@Test
public void comparingPinyin() {
final List<String> list = ListUtil.toList("成都", "北京", "上海", "深圳");
final List<String> list = ListUtil.of("成都", "北京", "上海", "深圳");
final List<String> ascendingOrderResult = ListUtil.of("北京", "成都", "上海", "深圳");
final List<String> descendingOrderResult = ListUtil.of("深圳", "上海", "成都", "北京");
final List<String> ascendingOrderResult = ListUtil.view("北京", "成都", "上海", "深圳");
final List<String> descendingOrderResult = ListUtil.view("深圳", "上海", "成都", "北京");
// 正序
list.sort(CompareUtil.comparingPinyin(e -> e));

View File

@ -2,8 +2,10 @@ package cn.hutool.core.compiler;
import cn.hutool.core.compress.ZipUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.reflect.ConstructorUtil;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
@ -16,6 +18,13 @@ import java.io.InputStream;
*/
public class JavaSourceCompilerTest {
@Test
@Ignore
public void compilerATest(){
final boolean compile = CompilerUtil.compile(FileUtil.file("test-compile/a/A.java").getAbsolutePath());
Assert.assertTrue(compile);
}
/**
* 测试编译Java源码
*/
@ -29,6 +38,7 @@ public class JavaSourceCompilerTest {
FileUtil.getInputStream("test-compile/a/A$1.class"),
FileUtil.getInputStream("test-compile/a/A$InnerClass.class")
});
Console.log(libFile.getAbsolutePath());
final ClassLoader classLoader = CompilerUtil.getCompiler(null)
.addSource(FileUtil.file("test-compile/b/B.java"))
.addSource("c.C", FileUtil.readUtf8String("test-compile/c/C.java"))

View File

@ -0,0 +1,46 @@
package cn.hutool.core.convert;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.collection.SetUtil;
import org.junit.Assert;
import org.junit.Test;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class CastUtilTest {
@Test
public void testCastToSuper() {
Collection<Integer> collection= ListUtil.of(1,2,3);
List<Integer> list = ListUtil.of(1, 2, 3);
Set<Integer> set = SetUtil.of(1, 2, 3);
Map<Integer, Integer> map = new HashMap<>();
map.put(1, 1);
Collection<Number> collection2 = CastUtil.castUp(collection);
collection2.add(new Double("123.1"));
Assert.assertSame(collection, collection2);
Collection<Integer> collection3 = CastUtil.castDown(collection2);
Assert.assertSame(collection2, collection3);
List<Number> list2 = CastUtil.castUp(list);
Assert.assertSame(list, list2);
List<Integer> list3 = CastUtil.castDown(list2);
Assert.assertSame(list2, list3);
Set<Number> set2 = CastUtil.castUp(set);
Assert.assertSame(set, set2);
Set<Integer> set3 = CastUtil.castDown(set2);
Assert.assertSame(set2, set3);
Map<Number, Serializable> map2 = CastUtil.castUp(map);
Assert.assertSame(map, map2);
Map<Integer, Number> map3 = CastUtil.castDown(map2);
Assert.assertSame(map2, map3);
}
}

View File

@ -1,12 +1,12 @@
package cn.hutool.core.convert;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.codec.HexUtil;
import cn.hutool.core.collection.SetUtil;
import cn.hutool.core.date.DateException;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.reflect.TypeReference;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.reflect.TypeReference;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.core.codec.HexUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
@ -15,6 +15,8 @@ import org.junit.Test;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
@ -293,7 +295,7 @@ public class ConvertTest {
public void toSetTest(){
final Set<Integer> result = Convert.convert(new TypeReference<Set<Integer>>() {
}, "1,2,3");
Assert.assertEquals(CollUtil.set(false, 1,2,3), result);
Assert.assertEquals(SetUtil.of(1,2,3), result);
}
@Getter
@ -383,4 +385,11 @@ public class ConvertTest {
final float b = Convert.toFloat(a);
Assert.assertEquals(a, b, 5);
}
@Test
public void localDateTimeToLocalDateTest(){
final LocalDateTime localDateTime = LocalDateTime.now();
final LocalDate convert = Convert.convert(LocalDate.class, localDateTime);
Assert.assertEquals(localDateTime.toLocalDate(), convert);
}
}

View File

@ -1,6 +1,6 @@
package cn.hutool.core.convert;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.reflect.TypeReference;
import org.junit.Assert;
import org.junit.Test;
@ -128,7 +128,7 @@ public class ConvertToCollectionTest {
public void toSetTest() {
final Object[] a = { "a", "", "", "", 1 };
final LinkedHashSet<?> set = Convert.convert(LinkedHashSet.class, a);
final ArrayList<?> list = CollUtil.newArrayList(set);
final ArrayList<?> list = ListUtil.of(set);
Assert.assertEquals("a", list.get(0));
Assert.assertEquals("", list.get(1));
Assert.assertEquals("", list.get(2));

View File

@ -31,4 +31,10 @@ public class NumberWordFormatTest {
final String format5 = NumberWordFormatter.formatSimple(438);
Assert.assertEquals("438", format5);
}
@Test
public void formatSimpleTest2(){
final String s = NumberWordFormatter.formatSimple(1000);
Assert.assertEquals("1k", s);
}
}

View File

@ -1,6 +1,6 @@
package cn.hutool.core.date;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.BetweenFormatter.Level;
import cn.hutool.core.date.format.FastDateFormat;
import cn.hutool.core.lang.Console;
@ -800,13 +800,13 @@ public class DateUtilTest {
Assert.assertEquals("20184", yearAndQuarter);
final LinkedHashSet<String> yearAndQuarters = DateUtil.yearAndQuarter(DateUtil.parse("2018-09-10"), DateUtil.parse("2018-12-20"));
final List<String> list = CollUtil.list(false, yearAndQuarters);
final List<String> list = ListUtil.of(false, yearAndQuarters);
Assert.assertEquals(2, list.size());
Assert.assertEquals("20183", list.get(0));
Assert.assertEquals("20184", list.get(1));
final LinkedHashSet<String> yearAndQuarters2 = DateUtil.yearAndQuarter(DateUtil.parse("2018-10-10"), DateUtil.parse("2018-12-10"));
final List<String> list2 = CollUtil.list(false, yearAndQuarters2);
final List<String> list2 = ListUtil.of(false, yearAndQuarters2);
Assert.assertEquals(1, list2.size());
Assert.assertEquals("20184", list2.get(0));
}

View File

@ -465,7 +465,7 @@ public class FileUtilTest {
@Test
@Ignore
public void appendLinesTest(){
final List<String> list = ListUtil.toList("a", "b", "c");
final List<String> list = ListUtil.of("a", "b", "c");
FileUtil.appendLines(list, FileUtil.file("d:/test/appendLines.txt"), CharsetUtil.UTF_8);
}

View File

@ -37,7 +37,7 @@ public class DictTest {
@Test
public void ofTest(){
final Dict dict = Dict.of(
final Dict dict = Dict.ofKvs(
"RED", "#FF0000",
"GREEN", "#00FF00",
"BLUE", "#0000FF"
@ -50,11 +50,11 @@ public class DictTest {
@Test
public void removeEqualTest(){
final Dict dict = Dict.of(
final Dict dict = Dict.ofKvs(
"key1", null
);
final Dict dict2 = Dict.of(
final Dict dict2 = Dict.ofKvs(
"key1", null
);

View File

@ -222,6 +222,7 @@ public class ValidatorTest {
public void isCarVinTest(){
Assert.assertTrue(Validator.isCarVin("LSJA24U62JG269225"));
Assert.assertTrue(Validator.isCarVin("LDC613P23A1305189"));
Assert.assertFalse(Validator.isCarVin("LOC613P23A1305189"));
}
@Test

View File

@ -1,10 +1,9 @@
package cn.hutool.core.lang;
import cn.hutool.core.collection.ListUtil;
import org.junit.Assert;
import org.junit.Test;
import cn.hutool.core.collection.CollUtil;
public class WeightRandomTest {
@Test
@ -15,6 +14,6 @@ public class WeightRandomTest {
random.add("C", 100);
final String result = random.next();
Assert.assertTrue(CollUtil.newArrayList("A", "B", "C").contains(result));
Assert.assertTrue(ListUtil.of("A", "B", "C").contains(result));
}
}

View File

@ -1,9 +1,10 @@
package cn.hutool.core.map;
import cn.hutool.core.lang.Pair;
import org.junit.Assert;
import org.junit.Test;
import java.util.Map;
public class CaseInsensitiveMapTest {
@Test
@ -25,8 +26,8 @@ public class CaseInsensitiveMapTest {
@Test
public void mergeTest(){
//https://github.com/dromara/hutool/issues/2086
final Pair<String, String> b = new Pair<>("a", "value");
final Pair<String, String> a = new Pair<>("A", "value");
final Map.Entry<String, String> b = MapUtil.entry("a", "value");
final Map.Entry<String, String> a = MapUtil.entry("A", "value");
final CaseInsensitiveMap<Object, Object> map = new CaseInsensitiveMap<>();
map.merge(b.getKey(), b.getValue(), (A, B) -> A);
map.merge(a.getKey(), a.getValue(), (A, B) -> A);

View File

@ -1,7 +1,7 @@
package cn.hutool.core.text;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.collection.SetUtil;
import org.junit.Assert;
import org.junit.Test;
@ -33,8 +33,8 @@ public class StrJoinerTest {
@Test
public void joinMultiArrayTest(){
final StrJoiner append = StrJoiner.of(",");
append.append(new Object[]{ListUtil.of("1", "2"),
CollUtil.newLinkedHashSet("3", "4")
append.append(new Object[]{ListUtil.view("1", "2"),
SetUtil.ofLinked("3", "4")
});
Assert.assertEquals("1,2,3,4", append.toString());
}

View File

@ -1,6 +1,6 @@
package cn.hutool.core.text.dfa;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import org.junit.Assert;
import org.junit.Test;
@ -27,7 +27,7 @@ public class DfaTest {
// 匹配到就不再继续匹配了因此大土豆不匹配
// 匹配到刚出锅就跳过这三个字了因此出锅不匹配由于刚首先被匹配因此长的被匹配最短匹配只针对第一个字相同选最短
final List<String> matchAll = tree.matchAll(text, -1, false, false);
Assert.assertEquals(matchAll, CollUtil.newArrayList("", "土^豆", "刚出锅"));
Assert.assertEquals(matchAll, ListUtil.of("", "土^豆", "刚出锅"));
}
/**
@ -43,7 +43,7 @@ public class DfaTest {
// 被匹配最短匹配原则大土豆被跳过土豆继续被匹配
// 刚出锅被匹配由于不跳过已经匹配的词出锅被匹配
final List<String> matchAll = tree.matchAll(text, -1, true, false);
Assert.assertEquals(matchAll, CollUtil.newArrayList("", "土^豆", "刚出锅", "出锅"));
Assert.assertEquals(matchAll, ListUtil.of("", "土^豆", "刚出锅", "出锅"));
}
/**
@ -59,7 +59,7 @@ public class DfaTest {
// 匹配到由于非密集匹配因此从下一个字符开始查找匹配到土豆接着被匹配
// 由于刚出锅被匹配由于非密集匹配出锅被跳过
final List<String> matchAll = tree.matchAll(text, -1, false, true);
Assert.assertEquals(matchAll, CollUtil.newArrayList("", "土^豆", "刚出锅"));
Assert.assertEquals(matchAll, ListUtil.of("", "土^豆", "刚出锅"));
}
@ -76,7 +76,7 @@ public class DfaTest {
// 匹配到由于到最长匹配因此大土豆接着被匹配由于不跳过已经匹配的关键词土豆继续被匹配
// 刚出锅被匹配由于不跳过已经匹配的词出锅被匹配
final List<String> matchAll = tree.matchAll(text, -1, true, true);
Assert.assertEquals(matchAll, CollUtil.newArrayList("", "大土^豆", "土^豆", "刚出锅", "出锅"));
Assert.assertEquals(matchAll, ListUtil.of("", "大土^豆", "土^豆", "刚出锅", "出锅"));
}
@ -112,7 +112,7 @@ public class DfaTest {
tree.addWord("tio");
final List<String> all = tree.matchAll("AAAAAAAt-ioBBBBBBB");
Assert.assertEquals(all, CollUtil.newArrayList("t-io"));
Assert.assertEquals(all, ListUtil.of("t-io"));
}
@Test

View File

@ -34,7 +34,7 @@ public class SensitiveUtilTest {
@Test
public void issue2126(){
SensitiveUtil.init(ListUtil.of("", "赵阿", "赵阿三"));
SensitiveUtil.init(ListUtil.view("", "赵阿", "赵阿三"));
final String result = SensitiveUtil.sensitiveFilter("赵阿三在做什么。", true, null);
Assert.assertEquals("***在做什么。", result);

View File

@ -1,8 +1,6 @@
package cn.hutool.core.tree;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.tree.Tree;
import cn.hutool.core.tree.TreeUtil;
import lombok.Data;
import org.junit.Assert;
import org.junit.Test;
@ -13,7 +11,7 @@ public class Issue2279Test {
@Test
public void buildSingleTest() {
final List<TestTree> list = ListUtil.of(
final List<TestTree> list = ListUtil.view(
// 模拟数据
new TestTree(1, 0, 1, 1),
new TestTree(2, 1, 2, 2),

View File

@ -1,10 +1,6 @@
package cn.hutool.core.tree;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.tree.Tree;
import cn.hutool.core.tree.TreeNode;
import cn.hutool.core.tree.TreeNodeConfig;
import cn.hutool.core.tree.TreeUtil;
import cn.hutool.core.collection.ListUtil;
import org.junit.Assert;
import org.junit.Test;
@ -18,7 +14,7 @@ import java.util.List;
*/
public class TreeTest {
// 模拟数据
static List<TreeNode<String>> nodeList = CollUtil.newArrayList();
static List<TreeNode<String>> nodeList = ListUtil.of();
static {
// 模拟数据

View File

@ -1,6 +1,6 @@
package cn.hutool.core.util;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import org.junit.Assert;
import org.junit.Test;
@ -323,7 +323,7 @@ public class ArrayUtilTest {
@Test
public void toArrayTest() {
final ArrayList<String> list = CollUtil.newArrayList("A", "B", "C", "D");
final ArrayList<String> list = ListUtil.of("A", "B", "C", "D");
final String[] array = ArrayUtil.toArray(list, String.class);
Assert.assertEquals("A", array[0]);
Assert.assertEquals("B", array[1]);

View File

@ -1,6 +1,6 @@
package cn.hutool.core.util;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import org.junit.Assert;
import org.junit.Test;
@ -18,13 +18,13 @@ public class EnumUtilTest {
@Test
public void getNamesTest() {
final List<String> names = EnumUtil.getNames(TestEnum.class);
Assert.assertEquals(CollUtil.newArrayList("TEST1", "TEST2", "TEST3"), names);
Assert.assertEquals(ListUtil.of("TEST1", "TEST2", "TEST3"), names);
}
@Test
public void getFieldValuesTest() {
final List<Object> types = EnumUtil.getFieldValues(TestEnum.class, "type");
Assert.assertEquals(CollUtil.newArrayList("type1", "type2", "type3"), types);
Assert.assertEquals(ListUtil.of("type1", "type2", "type3"), types);
}
@Test

View File

@ -47,49 +47,49 @@ public class IdcardUtilTest {
}
@Test
public void getAgeByIdCardTest() {
public void getAgeTest() {
final DateTime date = DateUtil.parse("2017-04-10");
final int age = IdcardUtil.getAgeByIdCard(ID_18, date);
final int age = IdcardUtil.getAge(ID_18, date);
Assert.assertEquals(age, 38);
final int age2 = IdcardUtil.getAgeByIdCard(ID_15, date);
final int age2 = IdcardUtil.getAge(ID_15, date);
Assert.assertEquals(age2, 28);
}
@Test
public void getBirthByIdCardTest() {
final String birth = IdcardUtil.getBirthByIdCard(ID_18);
public void getBirthTest() {
final String birth = IdcardUtil.getBirth(ID_18);
Assert.assertEquals(birth, "19781216");
final String birth2 = IdcardUtil.getBirthByIdCard(ID_15);
final String birth2 = IdcardUtil.getBirth(ID_15);
Assert.assertEquals(birth2, "19880730");
}
@Test
public void getProvinceByIdCardTest() {
final String province = IdcardUtil.getProvinceByIdCard(ID_18);
public void getProvinceTest() {
final String province = IdcardUtil.getProvince(ID_18);
Assert.assertEquals(province, "江苏");
final String province2 = IdcardUtil.getProvinceByIdCard(ID_15);
final String province2 = IdcardUtil.getProvince(ID_15);
Assert.assertEquals(province2, "内蒙古");
}
@Test
public void getCityCodeByIdCardTest() {
final String codeByIdCard = IdcardUtil.getCityCodeByIdCard(ID_18);
Assert.assertEquals("3210", codeByIdCard);
public void getCityCodeTest() {
final String code = IdcardUtil.getCityCode(ID_18);
Assert.assertEquals("3210", code);
}
@Test
public void getDistrictCodeByIdCardTest() {
final String codeByIdCard = IdcardUtil.getDistrictCodeByIdCard(ID_18);
Assert.assertEquals("321083", codeByIdCard);
public void getDistrictCodeTest() {
final String code = IdcardUtil.getDistrictCode(ID_18);
Assert.assertEquals("321083", code);
}
@Test
public void getGenderByIdCardTest() {
final int gender = IdcardUtil.getGenderByIdCard(ID_18);
public void getGenderTest() {
final int gender = IdcardUtil.getGender(ID_18);
Assert.assertEquals(1, gender);
}

View File

@ -62,6 +62,9 @@ public class NumberUtilTest {
Assert.assertTrue(NumberUtil.isInteger("0256"));
Assert.assertTrue(NumberUtil.isInteger("0"));
Assert.assertFalse(NumberUtil.isInteger("23.4"));
Assert.assertFalse(NumberUtil.isInteger(null));
Assert.assertFalse(NumberUtil.isInteger(""));
Assert.assertFalse(NumberUtil.isInteger(" "));
}
@Test
@ -71,6 +74,9 @@ public class NumberUtilTest {
Assert.assertTrue(NumberUtil.isLong("0256"));
Assert.assertTrue(NumberUtil.isLong("0"));
Assert.assertFalse(NumberUtil.isLong("23.4"));
Assert.assertFalse(NumberUtil.isLong(null));
Assert.assertFalse(NumberUtil.isLong(""));
Assert.assertFalse(NumberUtil.isLong(" "));
}
@Test
@ -293,6 +299,13 @@ public class NumberUtilTest {
Assert.assertEquals(1482L, v2.longValue());
}
@Test
public void parseHexNumberTest() {
// 千位分隔符去掉
final int v1 = NumberUtil.parseNumber("0xff").intValue();
Assert.assertEquals(255, v1);
}
@Test
public void parseLongTest() {
long number = NumberUtil.parseLong("0xFF");
@ -433,6 +446,25 @@ public class NumberUtilTest {
Assert.assertFalse(NumberUtil.isEven(a[4]));
}
@Test
public void toBigIntegerTest(){
final Number number=1123123;
final Number number2=1123123.123;
Assert.assertNotNull(NumberUtil.toBigInteger(number));
Assert.assertNotNull(NumberUtil.toBigInteger(number2));
}
@Test
public void divIntegerTest(){
final BigDecimal div = NumberUtil.div(100101300, (Number) 100);
Assert.assertEquals(1001013, div.intValue());
}
@Test
public void isDoubleTest(){
Assert.assertFalse(NumberUtil.isDouble(null));
Assert.assertFalse(NumberUtil.isDouble(""));
Assert.assertFalse(NumberUtil.isDouble(" "));
}
}

View File

@ -1,24 +1,46 @@
package cn.hutool.core.util;
import cn.hutool.core.clone.CloneSupport;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class ObjectUtilTest {
public class ObjUtilTest {
@Test
public void equalsTest(){
final Object a = null;
final Object b = null;
public void equalsTest() {
Object a = null;
Object b = null;
Assert.assertTrue(ObjUtil.equals(a, b));
a = new BigDecimal("1.1");
b = new BigDecimal("1.10");
Assert.assertTrue(ObjUtil.equals(a, b));
a = 127;
b = 127;
Assert.assertTrue(ObjUtil.equals(a, b));
a = 128;
b = 128;
Assert.assertTrue(ObjUtil.equals(a, b));
a = LocalDateTime.of(2022, 5, 29, 22, 11);
b = LocalDateTime.of(2022, 5, 29, 22, 11);
Assert.assertTrue(ObjUtil.equals(a, b));
a = 1;
b = 1.0;
Assert.assertFalse(ObjUtil.equals(a, b));
}
@Test
@ -33,6 +55,9 @@ public class ObjectUtilTest {
map.put("c", "c1");
length = ObjUtil.length(map);
Assert.assertEquals(3, length);
final Iterable<Integer> list = ListUtil.of(1, 2, 3);
Assert.assertEquals(3, ObjUtil.length(list));
}
@Test
@ -58,7 +83,7 @@ public class ObjectUtilTest {
@Test
public void toStringTest() {
final ArrayList<String> strings = CollUtil.newArrayList("1", "2");
final ArrayList<String> strings = ListUtil.of("1", "2");
final String result = ObjUtil.toString(strings);
Assert.assertEquals("[1, 2]", result);
}

View File

@ -1,6 +1,6 @@
package cn.hutool.core.util;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.Console;
import org.junit.Assert;
import org.junit.Ignore;
@ -15,13 +15,13 @@ public class RandomUtilTest {
@Test
public void randomEleSetTest(){
final Set<Integer> set = RandomUtil.randomEleSet(CollUtil.newArrayList(1, 2, 3, 4, 5, 6), 2);
final Set<Integer> set = RandomUtil.randomEleSet(ListUtil.of(1, 2, 3, 4, 5, 6), 2);
Assert.assertEquals(set.size(), 2);
}
@Test
public void randomElesTest(){
final List<Integer> result = RandomUtil.randomEles(CollUtil.newArrayList(1, 2, 3, 4, 5, 6), 2);
final List<Integer> result = RandomUtil.randomEles(ListUtil.of(1, 2, 3, 4, 5, 6), 2);
Assert.assertEquals(result.size(), 2);
}

View File

@ -1,6 +1,6 @@
package cn.hutool.core.util;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.regex.PatternPool;
import cn.hutool.core.regex.ReUtil;
@ -82,7 +82,7 @@ public class ReUtilTest {
public void findAllTest() {
// 查找所有匹配文本
final List<String> resultFindAll = ReUtil.findAll("\\w{2}", content, 0, new ArrayList<>());
final ArrayList<String> expected = CollUtil.newArrayList("ZZ", "Za", "aa", "bb", "bc", "cc", "12", "34");
final ArrayList<String> expected = ListUtil.of("ZZ", "Za", "aa", "bb", "bc", "cc", "12", "34");
Assert.assertEquals(expected, resultFindAll);
}

View File

@ -1,7 +1,8 @@
package cn.hutool.core.util;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.collection.SetUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.map.MapBuilder;
@ -109,7 +110,7 @@ public class XmlUtilTest {
final Map<String, Object> map = XmlUtil.xmlToMap(xml);
Assert.assertEquals(1, map.size());
Assert.assertEquals(CollUtil.newArrayList("张三", "李四"), map.get("name"));
Assert.assertEquals(ListUtil.of("张三", "李四"), map.get("name"));
}
@Test
@ -137,7 +138,7 @@ public class XmlUtilTest {
public void mapToXmlTest2() {
// 测试List
final Map<String, Object> map = MapBuilder.create(new LinkedHashMap<String, Object>())
.put("Town", CollUtil.newArrayList("town1", "town2"))
.put("Town", ListUtil.of("town1", "town2"))
.build();
final Document doc = XmlUtil.mapToXml(map, "City");
@ -157,7 +158,7 @@ public class XmlUtilTest {
@Test
public void readBySaxTest(){
final Set<String> eles = CollUtil.newHashSet(
final Set<String> eles = SetUtil.of(
"returnsms", "returnstatus", "message", "remainpoint", "taskID", "successCounts");
XmlUtil.readBySax(ResourceUtil.getStream("test.xml"), new DefaultHandler(){
@Override

View File

@ -1,5 +1,6 @@
package a;
import cn.hutool.core.lang.Console;
import cn.hutool.core.lang.ConsoleTable;
import cn.hutool.core.lang.caller.CallerUtil;
@ -10,15 +11,12 @@ public class A {
public A() {
new InnerClass() {{
int i = 0;
Class<?> caller = CallerUtil.getCaller(i);
final ConsoleTable t = new ConsoleTable();
t.addHeader("类名", "类加载器");
System.out.println("初始化 " + getClass() + " 的调用链为: ");
while (caller != null) {
t.addBody(caller.toString(), caller.getClassLoader().toString());
Console.log("初始化 " + getClass() + " 的调用链为: ");
Class<?> caller = CallerUtil.getCaller(i);
while (caller != null) {
Console.log("{} {}", caller, caller.getClassLoader());
caller = CallerUtil.getCaller(++i);
}
t.print();
}};
}
}

View File

@ -22,12 +22,10 @@
<dbcp2.version>2.9.0</dbcp2.version>
<tomcat-jdbc.version>10.0.20</tomcat-jdbc.version>
<druid.version>1.2.9</druid.version>
<hikariCP.version>2.4.13</hikariCP.version>
<mongo4.version>4.6.0</mongo4.version>
<hikariCP.version>4.0.3</hikariCP.version>
<sqlite.version>3.36.0.3</sqlite.version>
<!-- 此处固定2.5.x支持到JDK8 -->
<hsqldb.version>2.5.2</hsqldb.version>
<jedis.version>4.2.2</jedis.version>
</properties>
<dependencies>
@ -62,7 +60,7 @@
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP-java7</artifactId>
<artifactId>HikariCP</artifactId>
<version>${hikariCP.version}</version>
<exclusions>
<exclusion>
@ -81,7 +79,7 @@
<dependency>
<groupId>com.github.chris2018998</groupId>
<artifactId>beecp</artifactId>
<version>3.3.5</version>
<version>3.3.6</version>
<exclusions>
<exclusion>
<artifactId>slf4j-api</artifactId>
@ -94,31 +92,6 @@
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>${dbcp2.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-pool2</artifactId>
<groupId>org.apache.commons</groupId>
</exclusion>
</exclusions>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>${mongo4.version}</version>
<optional>true</optional>
</dependency>
<!-- Redis Java客户端 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${jedis.version}</version>
<exclusions>
<exclusion>
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
<optional>true</optional>
</dependency>
@ -156,7 +129,7 @@
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>10.2.0.jre8</version>
<version>10.2.1.jre8</version>
<scope>test</scope>
</dependency>
<dependency>

View File

@ -1,6 +1,6 @@
package cn.hutool.db;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.func.Func1;
import cn.hutool.db.dialect.Dialect;
import cn.hutool.db.handler.BeanListHandler;
@ -417,7 +417,7 @@ public abstract class AbstractDb<R extends AbstractDb<R>> extends DefaultConnect
* @throws DbRuntimeException SQL执行异常
*/
public int del(final String tableName, final String field, final Object value) throws DbRuntimeException {
return del(Entity.create(tableName).set(field, value));
return del(Entity.of(tableName).set(field, value));
}
/**
@ -470,7 +470,7 @@ public abstract class AbstractDb<R extends AbstractDb<R>> extends DefaultConnect
* @throws DbRuntimeException SQL执行异常
*/
public <T> Entity get(final String tableName, final String field, final T value) throws DbRuntimeException {
return this.get(Entity.create(tableName).set(field, value));
return this.get(Entity.of(tableName).set(field, value));
}
/**
@ -554,7 +554,7 @@ public abstract class AbstractDb<R extends AbstractDb<R>> extends DefaultConnect
* @throws DbRuntimeException SQL执行异常
*/
public <T> T find(final Entity where, final RsHandler<T> rsh, final String... fields) throws DbRuntimeException {
return find(CollUtil.newArrayList(fields), where, rsh);
return find(ListUtil.of(fields), where, rsh);
}
/**
@ -620,7 +620,7 @@ public abstract class AbstractDb<R extends AbstractDb<R>> extends DefaultConnect
* @throws DbRuntimeException SQL执行异常
*/
public List<Entity> findAll(final String tableName) throws DbRuntimeException {
return findAll(Entity.create(tableName));
return findAll(Entity.of(tableName));
}
/**
@ -633,7 +633,7 @@ public abstract class AbstractDb<R extends AbstractDb<R>> extends DefaultConnect
* @throws DbRuntimeException SQL执行异常
*/
public List<Entity> findBy(final String tableName, final String field, final Object value) throws DbRuntimeException {
return findAll(Entity.create(tableName).set(field, value));
return findAll(Entity.of(tableName).set(field, value));
}
/**
@ -661,7 +661,7 @@ public abstract class AbstractDb<R extends AbstractDb<R>> extends DefaultConnect
* @throws DbRuntimeException SQL执行异常
*/
public List<Entity> findLike(final String tableName, final String field, final String value, final LikeType likeType) throws DbRuntimeException {
return findAll(Entity.create(tableName).set(field, SqlUtil.buildLikeValue(value, likeType, true)));
return findAll(Entity.of(tableName).set(field, SqlUtil.buildLikeValue(value, likeType, true)));
}
/**

View File

@ -219,7 +219,7 @@ public class ActiveEntity extends Entity {
* @return this
*/
public ActiveEntity update(final String primaryKey) {
db.update(this, Entity.create().set(primaryKey, this.get(primaryKey)));
db.update(this, Entity.of().set(primaryKey, this.get(primaryKey)));
return this;
}
// -------------------------------------------------------------------------- CRUD end

View File

@ -139,7 +139,7 @@ public class DaoTemplate {
if (pk == null) {
return 0;
}
return this.del(Entity.create(tableName).set(primaryKeyField, pk));
return this.del(Entity.of(tableName).set(primaryKeyField, pk));
}
/**
@ -156,7 +156,7 @@ public class DaoTemplate {
return 0;
}
return this.del(Entity.create(tableName).set(field, value));
return this.del(Entity.of(tableName).set(field, value));
}
/**
@ -208,7 +208,7 @@ public class DaoTemplate {
throw new DbRuntimeException(StrUtil.format("Please determine `{}` for update", primaryKeyField));
}
final Entity where = Entity.create(tableName).set(primaryKeyField, pk);
final Entity where = Entity.of(tableName).set(primaryKeyField, pk);
final Entity record = entity.clone();
record.remove(primaryKeyField);
@ -252,7 +252,7 @@ public class DaoTemplate {
* @throws DbRuntimeException SQL执行异常
*/
public <T> Entity get(final String field, final T value) throws DbRuntimeException {
return this.get(Entity.create(tableName).set(field, value));
return this.get(Entity.of(tableName).set(field, value));
}
/**
@ -279,7 +279,7 @@ public class DaoTemplate {
* @throws DbRuntimeException SQL执行异常
*/
public <T> List<Entity> find(final String field, final T value) throws DbRuntimeException {
return this.find(Entity.create(tableName).set(field, value));
return this.find(Entity.of(tableName).set(field, value));
}
/**
@ -289,7 +289,7 @@ public class DaoTemplate {
* @throws DbRuntimeException SQL执行异常
*/
public List<Entity> findAll() throws DbRuntimeException {
return this.find(Entity.create(tableName));
return this.find(Entity.of(tableName));
}
/**
@ -377,7 +377,7 @@ public class DaoTemplate {
*/
private Entity fixEntity(Entity entity) {
if (null == entity) {
entity = Entity.create(tableName);
entity = Entity.of(tableName);
} else if (StrUtil.isBlank(entity.getTableName())) {
entity.setTableName(tableName);
}

View File

@ -1,6 +1,7 @@
package cn.hutool.db;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.SetUtil;
import cn.hutool.core.lang.func.Func0;
import cn.hutool.core.map.Dict;
import cn.hutool.core.reflect.MethodUtil;
@ -38,7 +39,7 @@ public class Entity extends Dict {
*
* @return Entity
*/
public static Entity create() {
public static Entity of() {
return new Entity();
}
@ -48,7 +49,7 @@ public class Entity extends Dict {
* @param tableName 表名
* @return Entity
*/
public static Entity create(final String tableName) {
public static Entity of(final String tableName) {
return new Entity(tableName);
}
@ -60,7 +61,7 @@ public class Entity extends Dict {
* @return Entity
*/
public static <T> Entity parse(final T bean) {
return create(null).parseBean(bean);
return of(null).parseBean(bean);
}
/**
@ -73,7 +74,7 @@ public class Entity extends Dict {
* @return Entity
*/
public static <T> Entity parse(final T bean, final boolean isToUnderlineCase, final boolean ignoreNullValue) {
return create(null).parseBean(bean, isToUnderlineCase, ignoreNullValue);
return of(null).parseBean(bean, isToUnderlineCase, ignoreNullValue);
}
/**
@ -84,7 +85,7 @@ public class Entity extends Dict {
* @return Entity
*/
public static <T> Entity parseWithUnderlineCase(final T bean) {
return create(null).parseBean(bean, true, true);
return of(null).parseBean(bean, true, true);
}
// --------------------------------------------------------------- Static method end
@ -155,7 +156,7 @@ public class Entity extends Dict {
*/
public Entity setFieldNames(final Collection<String> fieldNames) {
if (CollUtil.isNotEmpty(fieldNames)) {
this.fieldNames = CollUtil.newHashSet(true, fieldNames);
this.fieldNames = SetUtil.of(true, fieldNames);
}
return this;
}
@ -168,7 +169,7 @@ public class Entity extends Dict {
*/
public Entity setFieldNames(final String... fieldNames) {
if (ArrayUtil.isNotEmpty(fieldNames)) {
this.fieldNames = CollUtil.newLinkedHashSet(fieldNames);
this.fieldNames = SetUtil.ofLinked(fieldNames);
}
return this;
}

View File

@ -1,6 +1,5 @@
package cn.hutool.db.dialect;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.db.Entity;
import cn.hutool.db.Page;
import cn.hutool.db.sql.Order;
@ -134,7 +133,7 @@ public interface Dialect extends Serializable {
* @throws SQLException SQL执行异常
*/
default PreparedStatement psForCount(final Connection conn, final Query query) throws SQLException {
return psForFind(conn, query.clone().setFields(ListUtil.toList("count(1)")));
return psForCount(conn, SqlBuilder.create().query(query));
}
/**

View File

@ -9,7 +9,7 @@ import cn.hutool.core.text.StrUtil;
* @author Looly
*/
public enum DialectName {
ANSI, MYSQL, ORACLE, POSTGREESQL, SQLITE3, H2, SQLSERVER, SQLSERVER2012, PHOENIX;
ANSI, MYSQL, ORACLE, POSTGRESQL, SQLITE3, H2, SQLSERVER, SQLSERVER2012, PHOENIX;
/**
* 是否为指定数据库方言检查时不分区大小写

View File

@ -28,7 +28,7 @@ public class PostgresqlDialect extends AnsiSqlDialect{
@Override
public String dialectName() {
return DialectName.POSTGREESQL.name();
return DialectName.POSTGRESQL.name();
}
@Override

View File

@ -37,7 +37,7 @@ public class Column implements Serializable, Cloneable {
/**
* 大小或数据长度
*/
private int size;
private long size;
private Integer digit;
/**
* 是否为可空
@ -118,7 +118,7 @@ public class Column implements Serializable, Cloneable {
typeName = ReUtil.delLast("\\(\\d+\\)", typeName);
this.typeName = typeName;
this.size = columnMetaRs.getInt("COLUMN_SIZE");
this.size = columnMetaRs.getLong("COLUMN_SIZE");
this.isNullable = columnMetaRs.getBoolean("NULLABLE");
this.comment = columnMetaRs.getString("REMARKS");
this.columnDef = columnMetaRs.getString("COLUMN_DEF");
@ -238,7 +238,7 @@ public class Column implements Serializable, Cloneable {
*
* @return 大小或数据长度
*/
public int getSize() {
public long getSize() {
return size;
}
@ -248,7 +248,7 @@ public class Column implements Serializable, Cloneable {
* @param size 大小或数据长度
* @return this
*/
public Column setSize(final int size) {
public Column setSize(final long size) {
this.size = size;
return this;
}

View File

@ -172,7 +172,7 @@ public class MetaUtil {
*/
public static Entity createLimitedEntity(final DataSource ds, final String tableName) {
final String[] columnNames = getColumnNames(ds, tableName);
return Entity.create(tableName).setFieldNames(columnNames);
return Entity.of(tableName).setFieldNames(columnNames);
}
/**
@ -272,7 +272,7 @@ public class MetaUtil {
indexInfo.getColumnIndexInfoList().add(ColumnIndexInfo.create(rs));
}
}
table.setIndexInfoList(ListUtil.toList(indexInfoMap.values()));
table.setIndexInfoList(ListUtil.of(indexInfoMap.values()));
}
} catch (final SQLException e) {
throw new DbRuntimeException("Get columns error!", e);

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