com.landawn.abacus.util.N Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of abacus-android Show documentation
Show all versions of abacus-android Show documentation
A general and simple library for Android
/*
* Copyright (c) 2015, Haiyang Li.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.landawn.abacus.util;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Serializable;
import java.io.Writer;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.sql.SQLException;
import java.util.AbstractMap;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Deque;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import java.util.RandomAccess;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import com.landawn.abacus.DataSet;
import com.landawn.abacus.DirtyMarker;
import com.landawn.abacus.EntityId;
import com.landawn.abacus.annotation.Beta;
import com.landawn.abacus.annotation.NullSafe;
import com.landawn.abacus.core.EntityUtil;
import com.landawn.abacus.core.MapEntity;
import com.landawn.abacus.core.RowDataSet;
import com.landawn.abacus.exception.UncheckedException;
import com.landawn.abacus.exception.UncheckedIOException;
import com.landawn.abacus.exception.UncheckedSQLException;
import com.landawn.abacus.parser.DeserializationConfig;
import com.landawn.abacus.parser.JSONDeserializationConfig;
import com.landawn.abacus.parser.JSONDeserializationConfig.JDC;
import com.landawn.abacus.parser.JSONSerializationConfig;
import com.landawn.abacus.parser.XMLDeserializationConfig;
import com.landawn.abacus.parser.XMLDeserializationConfig.XDC;
import com.landawn.abacus.parser.XMLSerializationConfig;
import com.landawn.abacus.type.Type;
import com.landawn.abacus.type.TypeFactory;
import com.landawn.abacus.util.Fn.Factory;
import com.landawn.abacus.util.u.Nullable;
import com.landawn.abacus.util.u.Optional;
import com.landawn.abacus.util.u.OptionalDouble;
import com.landawn.abacus.util.function.BiPredicate;
import com.landawn.abacus.util.function.Function;
import com.landawn.abacus.util.function.IntFunction;
import com.landawn.abacus.util.function.Predicate;
import com.landawn.abacus.util.function.Supplier;
import com.landawn.abacus.util.function.ToDoubleFunction;
import com.landawn.abacus.util.function.ToFloatFunction;
import com.landawn.abacus.util.function.ToIntFunction;
import com.landawn.abacus.util.function.ToLongFunction;
/**
*
* Note: This class includes codes copied from Apache Commons Lang, Google Guava and other open source projects under the Apache License 2.0.
* The methods copied from other libraries/frameworks/projects may be modified in this class.
*
* Class N
is a general java utility class. It provides the most daily used operations for Object/primitive types/String/Array/Collection/Map/Entity...:
*
* When to throw exception? It's designed to avoid throwing any unnecessary
* exception if the contract defined by method is not broken. for example, if
* user tries to reverse a null or empty String. the input String will be
* returned. But exception will be thrown if trying to repeat/swap a null or
* empty string or operate Array/Collection by adding/removing...
*
* @author Haiyang Li
*
* @version $Revision: 0.8 $ 07/03/10
*
* @see com.landawn.abacus.util.IOUtil
* @see com.landawn.abacus.util.StringUtil
* @see com.landawn.abacus.util.Iterables
* @see com.landawn.abacus.util.Iterators
* @see com.landawn.abacus.util.Maps
* @see com.landawn.abacus.util.Primitives
* @see com.landawn.abacus.util.Array
* @see com.landawn.abacus.util.Seq
*/
public final class N {
private static final AsyncExecutor asyncExecutor = new AsyncExecutor(32, 256, 300L, TimeUnit.SECONDS);
// ... it has to be big enough to make it's safety to add element to
// ArrayBlockingQueue.
private static final int POOL_SIZE = Internals.POOL_SIZE;
// ...
static final String ELEMENT_SEPARATOR = Type.ELEMENT_SEPARATOR;
static final char[] ELEMENT_SEPARATOR_CHAR_ARRAY = Type.ELEMENT_SEPARATOR_CHAR_ARRAY;
/**
* An empty immutable {@code Boolean} array.
*/
static final Boolean[] EMPTY_BOOLEAN_OBJECT_ARRAY = new Boolean[0];
/**
* An empty immutable {@code Character} array.
*/
static final Character[] EMPTY_CHARACTER_OBJECT_ARRAY = new Character[0];
/**
* An empty immutable {@code Byte} array.
*/
static final Byte[] EMPTY_BYTE_OBJECT_ARRAY = new Byte[0];
/**
* An empty immutable {@code Short} array.
*/
static final Short[] EMPTY_SHORT_OBJECT_ARRAY = new Short[0];
/**
* An empty immutable {@code Integer} array.
*/
static final Integer[] EMPTY_INTEGER_OBJECT_ARRAY = new Integer[0];
/**
* An empty immutable {@code Long} array.
*/
static final Long[] EMPTY_LONG_OBJECT_ARRAY = new Long[0];
/**
* An empty immutable {@code Float} array.
*/
static final Float[] EMPTY_FLOAT_OBJECT_ARRAY = new Float[0];
/**
* An empty immutable {@code Double} array.
*/
static final Double[] EMPTY_DOUBLE_OBJECT_ARRAY = new Double[0];
/**
* An empty immutable {@code Class} array.
*/
static final Class>[] EMPTY_CLASS_ARRAY = new Class[0];
static final String NULL_STRING = "null".intern();
static final char[] NULL_CHAR_ARRAY = NULL_STRING.toCharArray();
static final String TRUE = Boolean.TRUE.toString().intern();
static final char[] TRUE_CHAR_ARRAY = TRUE.toCharArray();
static final String FALSE = Boolean.FALSE.toString().intern();
static final char[] FALSE_CHAR_ARRAY = FALSE.toCharArray();
// ...
static final char CHAR_0 = WD.CHAR_0;
/**
*
* @see JLF:
* Escape Sequences for Character and String Literals
* @since 2.2
*/
static final char CHAR_LF = WD.CHAR_LF;
/**
*
* @see JLF:
* Escape Sequences for Character and String Literals
* @since 2.2
*/
static final char CHAR_CR = WD.CHAR_CR;
// ...
/**
* The index value when an element is not found in a list or array:
* {@code -1}. This value is returned by methods in this class and can also
* be used in comparisons with values returned by various method from
* {@link java.util.List} .
*/
public static final int INDEX_NOT_FOUND = -1;
// ...
public static final String EMPTY_STRING = "".intern();
/**
* An empty immutable {@code boolean} array.
*/
public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0];
/**
* An empty immutable {@code char} array.
*/
public static final char[] EMPTY_CHAR_ARRAY = new char[0];
/**
* An empty immutable {@code byte} array.
*/
public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
/**
* An empty immutable {@code short} array.
*/
public static final short[] EMPTY_SHORT_ARRAY = new short[0];
/**
* An empty immutable {@code int} array.
*/
public static final int[] EMPTY_INT_ARRAY = new int[0];
/**
* An empty immutable {@code long} array.
*/
public static final long[] EMPTY_LONG_ARRAY = new long[0];
/**
* An empty immutable {@code float} array.
*/
public static final float[] EMPTY_FLOAT_ARRAY = new float[0];
/**
* An empty immutable {@code double} array.
*/
public static final double[] EMPTY_DOUBLE_ARRAY = new double[0];
/**
* An empty immutable {@code Boolean} array.
*/
public static final Boolean[] EMPTY_BOOLEAN_OBJ_ARRAY = new Boolean[0];
/**
* An empty immutable {@code Character} array.
*/
public static final Character[] EMPTY_CHAR_OBJ_ARRAY = new Character[0];
/**
* An empty immutable {@code Byte} array.
*/
public static final Byte[] EMPTY_BYTE_OBJ_ARRAY = new Byte[0];
/**
* An empty immutable {@code Short} array.
*/
public static final Short[] EMPTY_SHORT_OBJ_ARRAY = new Short[0];
/**
* An empty immutable {@code Integer} array.
*/
public static final Integer[] EMPTY_INT_OBJ_ARRAY = new Integer[0];
/**
* An empty immutable {@code Long} array.
*/
public static final Long[] EMPTY_LONG_OBJ_ARRAY = new Long[0];
/**
* An empty immutable {@code Float} array.
*/
public static final Float[] EMPTY_FLOAT_OBJ_ARRAY = new Float[0];
/**
* An empty immutable {@code Double} array.
*/
public static final Double[] EMPTY_DOUBLE_OBJ_ARRAY = new Double[0];
/**
* An empty immutable {@code String} array.
*/
public static final String[] EMPTY_STRING_ARRAY = new String[0];
/**
* An empty immutable {@code Object} array.
*/
public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];
@SuppressWarnings("rawtypes")
static final List EMPTY_LIST = Collections.emptyList();
@SuppressWarnings("rawtypes")
static final Set EMPTY_SET = Collections.emptySet();
@SuppressWarnings("rawtypes")
static final SortedSet EMPTY_SORTED_SET = Collections.emptySortedSet();
@SuppressWarnings("rawtypes")
static final NavigableSet EMPTY_NAVIGABLE_SET = Collections.emptyNavigableSet();
@SuppressWarnings("rawtypes")
static final Map EMPTY_MAP = Collections.emptyMap();
@SuppressWarnings("rawtypes")
static final SortedMap EMPTY_SORTED_MAP = Collections.emptySortedMap();
@SuppressWarnings("rawtypes")
static final NavigableMap EMPTY_NAVIGABLE_MAP = Collections.emptyNavigableMap();
@SuppressWarnings("rawtypes")
static final Iterator EMPTY_ITERATOR = Collections.emptyIterator();
@SuppressWarnings("rawtypes")
static final ListIterator EMPTY_LIST_ITERATOR = Collections.emptyListIterator();
// ...
static final Object NULL_MASK = new NullMask();
static final String BACKSLASH_ASTERISK = "*";
// ...
private static final int REVERSE_THRESHOLD = 18;
private static final int FILL_THRESHOLD = 25;
private static final int REPLACEALL_THRESHOLD = 11;
// ...
static final Random RAND = new SecureRandom();
@SuppressWarnings("rawtypes")
private static final Comparator NULL_MIN_COMPARATOR = Comparators.nullsFirst();
@SuppressWarnings("rawtypes")
private static final Comparator NULL_MAX_COMPARATOR = Comparators.nullsLast();
@SuppressWarnings("rawtypes")
private static final Comparator NATURAL_ORDER = Comparators.naturalOrder();
// ...
static final Map, Object> CLASS_EMPTY_ARRAY = new ConcurrentHashMap<>();
static {
CLASS_EMPTY_ARRAY.put(boolean.class, N.EMPTY_BOOLEAN_ARRAY);
CLASS_EMPTY_ARRAY.put(Boolean.class, N.EMPTY_BOOLEAN_OBJECT_ARRAY);
CLASS_EMPTY_ARRAY.put(char.class, N.EMPTY_CHAR_ARRAY);
CLASS_EMPTY_ARRAY.put(Character.class, N.EMPTY_CHARACTER_OBJECT_ARRAY);
CLASS_EMPTY_ARRAY.put(byte.class, N.EMPTY_BYTE_ARRAY);
CLASS_EMPTY_ARRAY.put(Byte.class, N.EMPTY_BYTE_OBJECT_ARRAY);
CLASS_EMPTY_ARRAY.put(short.class, N.EMPTY_SHORT_ARRAY);
CLASS_EMPTY_ARRAY.put(Short.class, N.EMPTY_SHORT_OBJECT_ARRAY);
CLASS_EMPTY_ARRAY.put(int.class, N.EMPTY_INT_ARRAY);
CLASS_EMPTY_ARRAY.put(Integer.class, N.EMPTY_INTEGER_OBJECT_ARRAY);
CLASS_EMPTY_ARRAY.put(long.class, N.EMPTY_LONG_ARRAY);
CLASS_EMPTY_ARRAY.put(Long.class, N.EMPTY_LONG_OBJECT_ARRAY);
CLASS_EMPTY_ARRAY.put(float.class, N.EMPTY_FLOAT_ARRAY);
CLASS_EMPTY_ARRAY.put(Float.class, N.EMPTY_FLOAT_OBJECT_ARRAY);
CLASS_EMPTY_ARRAY.put(double.class, N.EMPTY_DOUBLE_ARRAY);
CLASS_EMPTY_ARRAY.put(Double.class, N.EMPTY_DOUBLE_OBJECT_ARRAY);
CLASS_EMPTY_ARRAY.put(String.class, N.EMPTY_STRING_ARRAY);
CLASS_EMPTY_ARRAY.put(Object.class, N.EMPTY_OBJECT_ARRAY);
}
// ...
static final Map, Integer> CLASS_TYPE_ENUM = new HashMap<>();
static {
CLASS_TYPE_ENUM.put(boolean.class, 1);
CLASS_TYPE_ENUM.put(char.class, 2);
CLASS_TYPE_ENUM.put(byte.class, 3);
CLASS_TYPE_ENUM.put(short.class, 4);
CLASS_TYPE_ENUM.put(int.class, 5);
CLASS_TYPE_ENUM.put(long.class, 6);
CLASS_TYPE_ENUM.put(float.class, 7);
CLASS_TYPE_ENUM.put(double.class, 8);
CLASS_TYPE_ENUM.put(String.class, 9);
CLASS_TYPE_ENUM.put(boolean[].class, 11);
CLASS_TYPE_ENUM.put(char[].class, 12);
CLASS_TYPE_ENUM.put(byte[].class, 13);
CLASS_TYPE_ENUM.put(short[].class, 14);
CLASS_TYPE_ENUM.put(int[].class, 15);
CLASS_TYPE_ENUM.put(long[].class, 16);
CLASS_TYPE_ENUM.put(float[].class, 17);
CLASS_TYPE_ENUM.put(double[].class, 18);
CLASS_TYPE_ENUM.put(String[].class, 19);
CLASS_TYPE_ENUM.put(Boolean.class, 21);
CLASS_TYPE_ENUM.put(Character.class, 22);
CLASS_TYPE_ENUM.put(Byte.class, 23);
CLASS_TYPE_ENUM.put(Short.class, 24);
CLASS_TYPE_ENUM.put(Integer.class, 25);
CLASS_TYPE_ENUM.put(Long.class, 26);
CLASS_TYPE_ENUM.put(Float.class, 27);
CLASS_TYPE_ENUM.put(Double.class, 28);
}
// ...
private static final Map>, List extends Enum>>> enumListPool = new ObjectPool<>(POOL_SIZE);
private static final Map>, Set extends Enum>>> enumSetPool = new ObjectPool<>(POOL_SIZE);
private static final Map>, BiMap extends Enum>, String>> enumMapPool = new ObjectPool<>(POOL_SIZE);
private static final Map> nameTypePool = new ObjectPool<>(POOL_SIZE);
private static final Map, Type>> clsTypePool = new ObjectPool<>(POOL_SIZE);
// ...
static final Field listElementDataField;
static final Field listSizeField;
static volatile boolean isListElementDataFieldGettable = true;
static volatile boolean isListElementDataFieldSettable = true;
static {
Field tmp = null;
try {
tmp = String.class.getDeclaredField("offset");
} catch (Throwable e) {
// ignore.
}
if (tmp == null) {
try {
tmp = String.class.getDeclaredField("count");
} catch (Throwable e) {
// ignore.
}
}
if (tmp == null) {
try {
tmp = String.class.getDeclaredField("value");
} catch (Throwable e) {
// ignore.
}
}
tmp = null;
try {
tmp = ArrayList.class.getDeclaredField("elementData");
} catch (Throwable e) {
// ignore.
}
listElementDataField = tmp != null && tmp.getType().equals(Object[].class) ? tmp : null;
if (listElementDataField != null) {
listElementDataField.setAccessible(true);
}
tmp = null;
try {
tmp = ArrayList.class.getDeclaredField("size");
} catch (Throwable e) {
// ignore.
}
listSizeField = tmp != null && tmp.getType().equals(int.class) ? tmp : null;
if (listSizeField != null) {
listSizeField.setAccessible(true);
}
}
static final String[] charStringCache = new String[128];
static final int intStringCacheLow = -1001;
static final int intStringCacheHigh = 10001;
static final String[] intStringCache = new String[intStringCacheHigh - intStringCacheLow];
static final Map stringIntCache = new HashMap<>((int) (intStringCache.length * 1.5));
static {
for (int i = 0, j = intStringCacheLow, len = intStringCache.length; i < len; i++, j++) {
intStringCache[i] = Integer.valueOf(j).toString();
stringIntCache.put(intStringCache[i], j);
}
for (int i = 0; i < charStringCache.length; i++) {
charStringCache[i] = String.valueOf((char) i);
}
}
private static final int MIN_SIZE_FOR_COPY_ALL = 9;
/**
* Constructor for
*/
private N() {
// no instance();
}
@SuppressWarnings("unchecked")
public static Type typeOf(final String typeName) {
if (typeName == null) {
return null;
}
Type> type = nameTypePool.get(typeName);
if (type == null) {
type = TypeFactory.getType(typeName);
nameTypePool.put(typeName, type);
}
return (Type) type;
}
@SuppressWarnings("unchecked")
public static Type typeOf(final Class> cls) {
if (cls == null) {
return null;
}
Type> type = clsTypePool.get(cls);
if (type == null) {
type = TypeFactory.getType(cls);
clsTypePool.put(cls, type);
}
return (Type) type;
}
/**
*
* @param targetClass
* @param str
* @return the default value of the specified targetClass
if the specified string is null.
*/
@SuppressWarnings("unchecked")
public static T valueOf(final Class extends T> targetClass, final String str) {
return (str == null) ? defaultValueOf(targetClass) : (T) N.typeOf(targetClass).valueOf(str);
}
@SuppressWarnings("unchecked")
public static T defaultValueOf(final Class cls) {
return (T) N.typeOf(cls).defaultValue();
}
public static T defaultIfNull(final T obj, final T defaultForNull) {
return obj == null ? defaultForNull : obj;
}
@SuppressWarnings("unchecked")
// @SafeVarargs
// public static List> typeOf(final Class>... classes) {
// if (N.isNullOrEmpty(classes)) {
// return new ArrayList<>();
// }
//
// final List> result = new ArrayList<>(classes.length);
//
// for (int i = 0, len = classes.length; i < len; i++) {
// result.add((Type) typeOf(classes[i]));
// }
//
// return result;
// }
//
// @SuppressWarnings("unchecked")
// public static List> typeOf(final Collection extends Class>> classes) {
// final List> result = new ArrayList<>(classes.size());
//
// for (Class> cls : classes) {
// result.add((Type) typeOf(cls));
// }
//
// return result;
// }
public static String stringOf(final boolean val) {
return String.valueOf(val);
}
public static String stringOf(final char val) {
if (val < 128) {
return charStringCache[val];
}
return String.valueOf(val);
}
public static String stringOf(final byte val) {
if (val > intStringCacheLow && val < intStringCacheHigh) {
return intStringCache[val - intStringCacheLow];
}
return String.valueOf(val);
}
public static String stringOf(final short val) {
if (val > intStringCacheLow && val < intStringCacheHigh) {
return intStringCache[val - intStringCacheLow];
}
return String.valueOf(val);
}
public static String stringOf(final int val) {
if (val > intStringCacheLow && val < intStringCacheHigh) {
return intStringCache[val - intStringCacheLow];
}
return String.valueOf(val);
}
public static String stringOf(final long val) {
if (val > intStringCacheLow && val < intStringCacheHigh) {
return intStringCache[(int) (val - intStringCacheLow)];
}
return String.valueOf(val);
}
public static String stringOf(final float val) {
return String.valueOf(val);
}
public static String stringOf(final double val) {
return String.valueOf(val);
}
/**
*
* @param obj
* @return null
if the specified object is null.
*/
public static String stringOf(final Object obj) {
return (obj == null) ? null : N.typeOf(obj.getClass()).stringOf(obj);
}
public static > List enumListOf(final Class enumClass) {
List enumList = (List) enumListPool.get(enumClass);
if (enumList == null) {
enumList = ImmutableList.of(N.asList(enumClass.getEnumConstants()));
enumListPool.put(enumClass, enumList);
}
return enumList;
}
public static > Set enumSetOf(final Class enumClass) {
Set enumSet = (Set) enumSetPool.get(enumClass);
if (enumSet == null) {
enumSet = ImmutableSet.of(EnumSet.allOf(enumClass));
enumSetPool.put(enumClass, enumSet);
}
return enumSet;
}
public static > BiMap enumMapOf(final Class enumClass) {
BiMap enumMap = (BiMap) enumMapPool.get(enumClass);
if (enumMap == null) {
final EnumMap keyMap = new EnumMap<>(enumClass);
final Map valueMap = new HashMap<>();
for (final E e : enumClass.getEnumConstants()) {
keyMap.put(e, e.name());
valueMap.put(e.name(), e);
}
enumMap = new BiMap<>(ImmutableMap.of(keyMap), ImmutableMap.of(valueMap));
enumMapPool.put(enumClass, enumMap);
}
return enumMap;
}
/**
* Method newInstance.
*
* @param cls
* @return T
*/
public static T newInstance(final Class cls) {
if (Modifier.isAbstract(cls.getModifiers())) {
if (cls.equals(Map.class)) {
return (T) new HashMap<>();
} else if (cls.equals(List.class)) {
return (T) new ArrayList<>();
} else if (cls.equals(Set.class)) {
return (T) new HashSet<>();
} else if (cls.equals(Queue.class)) {
return (T) new LinkedList<>();
} else if (cls.equals(Deque.class)) {
return (T) new LinkedList<>();
} else if (cls.equals(SortedSet.class) || cls.equals(NavigableSet.class)) {
return (T) new TreeSet<>();
} else if (cls.equals(SortedMap.class) || cls.equals(NavigableMap.class)) {
return (T) new TreeMap<>();
}
}
try {
if (Modifier.isStatic(cls.getModifiers()) == false && (cls.isAnonymousClass() || cls.isMemberClass())) {
// http://stackoverflow.com/questions/2097982/is-it-possible-to-create-an-instance-of-nested-class-using-java-reflection
final List> toInstantiate = new ArrayList<>();
Class> parent = cls.getEnclosingClass();
do {
toInstantiate.add(parent);
parent = parent.getEnclosingClass();
} while (parent != null && Modifier.isStatic(parent.getModifiers()) == false && (parent.isAnonymousClass() || parent.isMemberClass()));
if (parent != null) {
toInstantiate.add(parent);
}
N.reverse(toInstantiate);
Object instance = null;
for (Class> current : toInstantiate) {
instance = instance == null ? invoke(ClassUtil.getDeclaredConstructor(current))
: invoke(ClassUtil.getDeclaredConstructor(current, instance.getClass()), instance);
}
return invoke(ClassUtil.getDeclaredConstructor(cls, instance.getClass()), instance);
} else {
return invoke(ClassUtil.getDeclaredConstructor(cls));
}
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw N.toRuntimeException(e);
}
}
@SuppressWarnings("unchecked")
private static T invoke(final Constructor c, final Object... args)
throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
if (c.isAccessible() == false) {
c.setAccessible(true);
}
return c.newInstance(args);
}
public static T newProxyInstance(final Class interfaceClass, final InvocationHandler h) {
return newProxyInstance(N.asArray(interfaceClass), h);
}
/**
* Refer to {@code java.lang.reflect}
*
* @param interfaceClasses
* @param h
* @return
*/
public static T newProxyInstance(final Class>[] interfaceClasses, final InvocationHandler h) {
return (T) Proxy.newProxyInstance(N.class.getClassLoader(), interfaceClasses, h);
}
/**
* Method newArray.
*
* @param componentType
* @param length
* @return T[]
*/
@SuppressWarnings("unchecked")
public static T newArray(final Class> componentType, final int length) {
// if (length == 0) {
// final Object result = CLASS_EMPTY_ARRAY.get(componentType);
//
// if (result != null) {
// return (T) result;
// }
// }
return (T) Array.newInstance(componentType, length);
}
@SuppressWarnings("unchecked")
public static T newEntity(final Class cls) {
return newEntity(cls, null);
}
public static T newEntity(final Class cls, final String entityName) {
if (MapEntity.class.isAssignableFrom(cls)) {
return (T) asMapEntity(entityName);
}
final Class> enclosingClass = ClassUtil.getEnclosingClass(cls);
if (enclosingClass == null || Modifier.isStatic(cls.getModifiers())) {
return newInstance(cls);
} else {
return ClassUtil.invokeConstructor(ClassUtil.getDeclaredConstructor(cls, enclosingClass), newInstance(enclosingClass));
}
}
/**
* Returns a set backed by the specified map.
*
* @param map the backing map
* @return the set backed by the map
* @see Collections#newSetFromMap(Map)
*/
public static Set newSetFromMap(final Map map) {
return Collections.newSetFromMap(map);
}
public static int initHashCapacity(final int size) {
N.checkArgNotNegative(size, "size");
if (size == 0) {
return 0;
}
int res = size < MAX_HASH_LENGTH ? (int) (size * 1.25) + 1 : MAX_ARRAY_SIZE;
switch (res / 64) {
case 0:
case 1:
return res;
case 2:
case 3:
case 4:
return 128;
default:
return 256;
}
}
public static ArrayList newArrayList() {
return new ArrayList<>();
}
public static ArrayList newArrayList(int initialCapacity) {
return new ArrayList<>(initialCapacity);
}
public static ArrayList newArrayList(Collection extends T> c) {
return N.isNullOrEmpty(c) ? new ArrayList() : new ArrayList(c);
}
public static LinkedList newLinkedList() {
return new LinkedList<>();
}
public static LinkedList newLinkedList(Collection extends T> c) {
return N.isNullOrEmpty(c) ? new LinkedList() : new LinkedList<>(c);
}
public static HashSet newHashSet() {
return new HashSet<>();
}
/**
*
* @param initialCapacity
* @return
*/
public static HashSet newHashSet(int initialCapacity) {
return new HashSet<>(initialCapacity);
}
public static HashSet newHashSet(Collection extends T> c) {
return N.isNullOrEmpty(c) ? new HashSet() : new HashSet<>(c);
}
public static LinkedHashSet newLinkedHashSet() {
return new LinkedHashSet<>();
}
/**
*
* @param initialCapacity
* @return
*/
public static LinkedHashSet newLinkedHashSet(int initialCapacity) {
return new LinkedHashSet<>(initialCapacity);
}
public static LinkedHashSet newLinkedHashSet(Collection extends T> c) {
return N.isNullOrEmpty(c) ? new LinkedHashSet() : new LinkedHashSet<>(c);
}
@SuppressWarnings("rawtypes")
public static TreeSet newTreeSet() {
return new TreeSet<>();
}
public static TreeSet newTreeSet(Comparator super T> comparator) {
return new TreeSet<>(comparator);
}
@SuppressWarnings("rawtypes")
public static TreeSet newTreeSet(Collection extends T> c) {
return N.isNullOrEmpty(c) ? new TreeSet() : new TreeSet<>(c);
}
public static TreeSet newTreeSet(SortedSet c) {
return N.isNullOrEmpty(c) ? new TreeSet() : new TreeSet<>(c);
}
public static Multiset newMultiset() {
return new Multiset<>();
}
public static Multiset newMultiset(final int initialCapacity) {
return new Multiset<>(initialCapacity);
}
@SuppressWarnings("rawtypes")
public static Multiset newMultiset(final Class extends Map> valueMapType) {
return new Multiset<>(valueMapType);
}
public static Multiset newMultiset(final Supplier extends Map> mapSupplier) {
return new Multiset<>(mapSupplier);
}
public static Multiset newMultiset(final Collection extends T> c) {
return new Multiset<>(c);
}
public static ArrayDeque newArrayDeque() {
return new ArrayDeque<>();
}
/**
* Constructs an empty array deque with an initial capacity sufficient to hold the specified number of elements.
*
* @param numElements lower bound on initial capacity of the deque.
* @return
*/
public static ArrayDeque newArrayDeque(int numElements) {
return new ArrayDeque<>(numElements);
}
/**
* Constructs a deque containing the elements of the specified collection, in the order they are returned by the collection's iterator.
*
* @param c
* @return
*/
public static ArrayDeque newArrayDeque(Collection extends E> c) {
return new ArrayDeque<>(c);
}
public static Map.Entry newEntry(K key, V value) {
return new AbstractMap.SimpleEntry<>(key, value);
}
public static ImmutableEntry newImmutableEntry(K key, V value) {
return new ImmutableEntry<>(key, value);
}
public static HashMap newHashMap() {
return new HashMap<>();
}
/**
*
* @param initialCapacity
* @return
*/
public static HashMap newHashMap(int initialCapacity) {
return new HashMap<>(initialCapacity);
}
public static HashMap newHashMap(Map extends K, ? extends V> m) {
return N.isNullOrEmpty(m) ? new HashMap() : new HashMap(m);
}
public static HashMap newHashMap(final Collection extends V> c, final Try.Function super V, ? extends K, E> keyMapper)
throws E {
N.checkArgNotNull(keyMapper);
if (isNullOrEmpty(c)) {
return new HashMap<>();
}
final HashMap result = new HashMap<>(N.initHashCapacity(c.size()));
for (V v : c) {
result.put(keyMapper.apply(v), v);
}
return result;
}
public static LinkedHashMap newLinkedHashMap() {
return new LinkedHashMap<>();
}
/**
*
* @param initialCapacity
* @return
*/
public static LinkedHashMap newLinkedHashMap(int initialCapacity) {
return new LinkedHashMap<>(initialCapacity);
}
public static LinkedHashMap newLinkedHashMap(Map extends K, ? extends V> m) {
return N.isNullOrEmpty(m) ? new LinkedHashMap() : new LinkedHashMap(m);
}
public static LinkedHashMap newLinkedHashMap(final Collection extends V> c,
final Try.Function super V, ? extends K, E> keyMapper) throws E {
N.checkArgNotNull(keyMapper);
if (isNullOrEmpty(c)) {
return new LinkedHashMap<>();
}
final LinkedHashMap result = new LinkedHashMap<>(N.initHashCapacity(c.size()));
for (V v : c) {
result.put(keyMapper.apply(v), v);
}
return result;
}
@SuppressWarnings("rawtypes")
public static TreeMap newTreeMap() {
return new TreeMap<>();
}
public static TreeMap newTreeMap(Comparator comparator) {
return new TreeMap<>(comparator);
}
@SuppressWarnings("rawtypes")
public static TreeMap newTreeMap(Map extends K, ? extends V> m) {
return N.isNullOrEmpty(m) ? new TreeMap() : new TreeMap(m);
}
public static TreeMap newTreeMap(SortedMap m) {
return N.isNullOrEmpty(m) ? new TreeMap() : new TreeMap(m);
}
public static IdentityHashMap newIdentityHashMap() {
return new IdentityHashMap<>();
}
/**
*
* @param initialCapacity
* @return
*/
public static IdentityHashMap newIdentityHashMap(int initialCapacity) {
return new IdentityHashMap<>(initialCapacity);
}
public static IdentityHashMap newIdentityHashMap(Map extends K, ? extends V> m) {
return N.isNullOrEmpty(m) ? new IdentityHashMap() : new IdentityHashMap(m);
}
public static ConcurrentHashMap newConcurrentHashMap() {
return new ConcurrentHashMap<>();
}
/**
*
* @param initCapacity the initial capacity of new HashSet
* @return
*/
public static ConcurrentHashMap newConcurrentHashMap(int initialCapacity) {
return new ConcurrentHashMap<>(initialCapacity);
}
public static ConcurrentHashMap newConcurrentHashMap(Map extends K, ? extends V> m) {
return N.isNullOrEmpty(m) ? new ConcurrentHashMap() : new ConcurrentHashMap(m);
}
public static BiMap newBiMap() {
return new BiMap<>();
}
public static BiMap newBiMap(int initialCapacity) {
return new BiMap<>(initialCapacity);
}
public static BiMap newBiMap(int initialCapacity, float loadFactor) {
return new BiMap<>(initialCapacity, loadFactor);
}
@SuppressWarnings("rawtypes")
public static BiMap newBiMap(final Class extends Map> keyMapType, final Class extends Map> valueMapType) {
return new BiMap<>(keyMapType, valueMapType);
}
public static BiMap newBiMap(final Supplier extends Map> keyMapSupplier, final Supplier extends Map> valueMapSupplier) {
return new BiMap<>(keyMapSupplier, valueMapSupplier);
}
public static > Multimap newMultimap(final Supplier extends Map> mapSupplier,
final Supplier extends V> valueSupplier) {
return new Multimap<>(mapSupplier, valueSupplier);
}
public static ListMultimap newListMultimap() {
return new ListMultimap<>();
}
public static ListMultimap newListMultimap(final int initialCapacity) {
return new ListMultimap<>(initialCapacity);
}
public static ListMultimap newListMultimap(final Map extends K, ? extends E> m) {
final ListMultimap multiMap = newListMultimap();
multiMap.putAll(m);
return multiMap;
}
public static ListMultimap newListLinkedMultimap() {
return new ListMultimap<>(LinkedHashMap.class, ArrayList.class);
}
public static ListMultimap newListLinkedMultimap(final int initialCapacity) {
return new ListMultimap<>(new LinkedHashMap>(initialCapacity), ArrayList.class);
}
public static ListMultimap newListLinkedMultimap(final Map extends K, ? extends E> m) {
final ListMultimap multiMap = new ListMultimap<>(new LinkedHashMap>(), ArrayList.class);
multiMap.putAll(m);
return multiMap;
}
public static , E> ListMultimap newListSortedMultimap() {
return new ListMultimap<>(new TreeMap>(), ArrayList.class);
}
public static , E> ListMultimap newListSortedMultimap(final Map extends K, ? extends E> m) {
final ListMultimap multiMap = new ListMultimap<>(new TreeMap>(), ArrayList.class);
multiMap.putAll(m);
return multiMap;
}
@SuppressWarnings("rawtypes")
public static ListMultimap newListMultimap(final Class extends Map> mapType) {
return new ListMultimap<>(mapType, ArrayList.class);
}
@SuppressWarnings("rawtypes")
public static ListMultimap newListMultimap(final Class extends Map> mapType, final Class extends List> valueType) {
return new ListMultimap<>(mapType, valueType);
}
public static ListMultimap newListMultimap(final Supplier extends Map>> mapSupplier,
final Supplier extends List> valueSupplier) {
return new ListMultimap<>(mapSupplier, valueSupplier);
}
public static SetMultimap newSetMultimap() {
return new SetMultimap<>();
}
public static SetMultimap newSetMultimap(final int initialCapacity) {
return new SetMultimap<>(initialCapacity);
}
public static SetMultimap newSetMultimap(final Map extends K, ? extends E> m) {
final SetMultimap multiMap = newSetMultimap();
multiMap.putAll(m);
return multiMap;
}
public static SetMultimap newSetLinkedMultimap() {
return new SetMultimap<>(LinkedHashMap.class, HashSet.class);
}
public static SetMultimap newSetLinkedMultimap(final int initialCapacity) {
return new SetMultimap<>(new LinkedHashMap>(initialCapacity), HashSet.class);
}
public static SetMultimap newSetLinkedMultimap(final Map extends K, ? extends E> m) {
final SetMultimap multiMap = new SetMultimap<>(new LinkedHashMap>(), HashSet.class);
multiMap.putAll(m);
return multiMap;
}
public static , E> SetMultimap newSetSortedMultimap() {
return new SetMultimap<>(new TreeMap>(), HashSet.class);
}
public static , E> SetMultimap newSetSortedMultimap(final Map extends K, ? extends E> m) {
final SetMultimap multiMap = new SetMultimap<>(new TreeMap>(), HashSet.class);
multiMap.putAll(m);
return multiMap;
}
@SuppressWarnings("rawtypes")
public static SetMultimap newSetMultimap(final Class extends Map> mapType) {
return new SetMultimap<>(mapType, HashSet.class);
}
@SuppressWarnings("rawtypes")
public static SetMultimap newSetMultimap(final Class extends Map> mapType, final Class extends Set> valueType) {
return new SetMultimap<>(mapType, valueType);
}
public static SetMultimap newSetMultimap(final Supplier extends Map>> mapSupplier,
final Supplier extends Set> valueSupplier) {
return new SetMultimap<>(mapSupplier, valueSupplier);
}
static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
static final int MAX_HASH_LENGTH = (int) (MAX_ARRAY_SIZE / 1.25) - 1;
public static DataSet newEmptyDataSet() {
return new RowDataSet(new ArrayList(), new ArrayList>());
}
public static DataSet newEmptyDataSet(final Collection columnNames) {
if (N.isNullOrEmpty(columnNames)) {
return newEmptyDataSet();
}
final List> columnList = new ArrayList<>(columnNames.size());
for (int i = 0, size = columnNames.size(); i < size; i++) {
columnList.add(new ArrayList<>(0));
}
return new RowDataSet(new ArrayList