org.zodiac.sdk.json.util.CollectionUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of zodiac-sdk-json Show documentation
Show all versions of zodiac-sdk-json Show documentation
Zodiac SDK JSON(JavaScript Object Notation)
package org.zodiac.sdk.json.util;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.TreeSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class CollectionUtil {
private CollectionUtil() {
}
private static final Logger LOGGER = LoggerFactory.getLogger(CollectionUtil.class);
public static Collection createCollection(Type type, boolean isThrow) {
if (type == null) {
return new ArrayList();
}
/*最常用的放前面*/
if (type == ArrayList.class) {
return new ArrayList();
}
Class> rawClass = TypeUtil.getRawClass(type);
Collection list;
if (rawClass == AbstractCollection.class //
|| rawClass == Collection.class) {
list = new ArrayList();
} else if (rawClass.isAssignableFrom(HashSet.class)) {
list = new HashSet();
} else if (rawClass.isAssignableFrom(LinkedHashSet.class)) {
list = new LinkedHashSet();
} else if (rawClass.isAssignableFrom(TreeSet.class)) {
list = new TreeSet();
} else if (rawClass.isAssignableFrom(ArrayList.class)) {
list = new ArrayList();
} else if (rawClass.isAssignableFrom(EnumSet.class)) {
Type itemType;
if (type instanceof ParameterizedType) {
itemType = ((ParameterizedType) type).getActualTypeArguments()[0];
} else {
itemType = Object.class;
}
list = EnumSet.noneOf((Class) itemType);
} else {
try {
list = (Collection) rawClass.newInstance();
} catch (Exception e) {
if (isThrow) {
throw new IllegalArgumentException("Create instance error, class " + rawClass.getName());
} else {
return null;
}
}
}
return list;
}
public static Map createMap(Class> mapType) {
if (mapType.isAssignableFrom(AbstractMap.class)) {
return new HashMap<>();
} else {
try {
return (Map) mapType.getConstructor().newInstance();
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException | NoSuchMethodException | SecurityException e) {
LOGGER.error("{} : {}", CollectionUtil.class.getSimpleName(), e.getMessage());
return null;
}
}
}
}