package com.dsh.utils;
|
|
import com.alibaba.fastjson.util.ParameterizedTypeImpl;
|
import org.apache.commons.lang3.ArrayUtils;
|
import sun.misc.Unsafe;
|
|
import java.lang.reflect.Field;
|
import java.lang.reflect.ParameterizedType;
|
import java.lang.reflect.Type;
|
|
/**
|
* * @author: lihong .
|
* * @email: 765907456@qq.com .
|
* * @createTime: 2019/10/12 下午5:24 .
|
* * @description: .
|
**/
|
public class ObjectUtils {
|
private static Unsafe UNSAFE;
|
|
static {
|
try {
|
Field field = Unsafe.class.getDeclaredField("theUnsafe");
|
field.setAccessible(true);
|
UNSAFE = (Unsafe) field.get(null);
|
} catch (NoSuchFieldException e) {
|
e.printStackTrace();
|
} catch (IllegalAccessException e) {
|
e.printStackTrace();
|
}
|
}
|
|
/**
|
* 实例化对象.不调用构造函数
|
*
|
* @param clazz
|
* @param <T>
|
* @return
|
*/
|
public static <T> T newInstance(Class clazz) {
|
try {
|
return (T) UNSAFE.allocateInstance(clazz);
|
} catch (InstantiationException e) {
|
e.printStackTrace();
|
}
|
return null;
|
}
|
|
|
/**
|
* 构建泛型类型.
|
*
|
* @param types
|
* @return
|
*/
|
public static Type buildType(Type... types) {
|
ParameterizedTypeImpl beforeType = null;
|
if (types.length == 1) {
|
return types[0];
|
}
|
if (types != null && types.length > 0) {
|
for (int i = types.length - 1; i > 0; --i) {
|
beforeType = new ParameterizedTypeImpl(new Type[]{beforeType == null ? types[i] : beforeType}, null, types[i - 1]);
|
}
|
}
|
return beforeType;
|
}
|
|
/**
|
* 获取类真实泛型类型.
|
*
|
* @param clazz 类型
|
* @param genericIndex 泛型位置
|
* @return
|
*/
|
public static Class getGenericClassRealType(Class clazz, int genericIndex) {
|
Type genericSuperclass = clazz.getGenericSuperclass();
|
if (genericSuperclass instanceof ParameterizedType) {
|
ParameterizedType parameterizedType = (ParameterizedType) clazz.getGenericSuperclass();
|
return getGenericRealType(parameterizedType, genericIndex);
|
}
|
return null;
|
}
|
|
private static Class getGenericRealType(ParameterizedType parameterizedType, int genericIndex) {
|
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
|
if (actualTypeArguments.length <= genericIndex) {
|
return null;
|
}
|
return (Class) actualTypeArguments[genericIndex];
|
}
|
|
public static Class getGenericInterfaceRealType(Class clazz, Type interfaceType, int genericIndex) {
|
Type[] genericInterfaces = clazz.getGenericInterfaces();
|
if (ArrayUtils.isEmpty(genericInterfaces)) {
|
return null;
|
}
|
for (Type genericInterface : genericInterfaces) {
|
if (genericInterface instanceof ParameterizedType && ((ParameterizedType) genericInterface).getRawType().equals(interfaceType)) {
|
return getGenericRealType((ParameterizedType) genericInterface, genericIndex);
|
}
|
}
|
return null;
|
}
|
|
public static String toBinaryString(Integer str) {
|
String s = String.valueOf(Integer.toBinaryString(str));
|
return s.substring(s.length() - 2, s.length() - 1);
|
}
|
}
|