第0章:简介
第1章:Class工具类
Class工具类ClassUtils.java如下:
package com.lsl.core.reflection;
import java.beans.Introspector;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Class工具类
* copy from spring core or commons lang package
* @author <a href="mailto:417877417@qq.com">menergy</a>
* @version 2013-11-11
*/
public abstract class ClassUtils {
/** 数组类名后缀: "[]" */
public static final String ARRAY_SUFFIX = "[]";
/** 内在数组类名前缀: "[" */
private static final String INTERNAL_ARRAY_PREFIX = "[";
/**内在非原始数组类名前缀: "[L" */
private static final String NON_PRIMITIVE_ARRAY_PREFIX = "[L";
/** 包分隔符 '.' */
private static final char PACKAGE_SEPARATOR = '.';
/** 内部类分隔符 '$' */
private static final char INNER_CLASS_SEPARATOR = '$';
/** code生成库(CGLIB) 类分隔符 "$$" */
public static final String CGLIB_CLASS_SEPARATOR = "$$";
/** ".class"文件后缀 */
public static final String CLASS_FILE_SUFFIX = ".class";
/**
* Map<基本数据类型封装类,基本数据类型类>
* example: Integer.class -> int.class.
*/
private static final Map<Class<?>, Class<?>> wrapperClassToPrimitiveClassMap = new HashMap<Class<?>, Class<?>>(8);
/**
* Map<基本数据类型类, 基本数据类型封装类>
* example:int.class -> Integer.class.
*/
private static final Map<Class<?>, Class<?>> primitiveClassToWrapperClassMap = new HashMap<Class<?>, Class<?>>(8);
/**
* Map<基本数据类型名, 基本数据类型类>
* example: "int" -> "int.class".
*/
private static final Map<String, Class<?>> primitiveNameToPrimitiveClassMap = new HashMap<String, Class<?>>(32);
/**
* Map: 普通"java.lang"类名做主键,对应的Class作为值
*/
private static final Map<String, Class<?>> commonClassCache = new HashMap<String, Class<?>>(32);
/**
* Map<基本数据类型,数组类名称中基本数据类型的缩写>
* example: Map<"int", "I">
*/
private static final Map<String, String> abbreviationMap = new HashMap<String, String>();
/**
* Map<数组类名称中基本数据类型的缩写,基本数据类型>
* example: Map<"I", "int">
*/
private static final Map<String, String> reverseAbbreviationMap = new HashMap<String, String>();
/**
* 添加基本数据类型和数组类名称中基本数据类型的缩写的关系
*
* @param primitive
* @param abbreviation
*/
private static void addAbbreviation(String primitive, String abbreviation) {
abbreviationMap.put(primitive, abbreviation);
reverseAbbreviationMap.put(abbreviation, primitive);
}
static {
addAbbreviation("int", "I");
addAbbreviation("boolean", "Z");
addAbbreviation("float", "F");
addAbbreviation("long", "J");
addAbbreviation("short", "S");
addAbbreviation("byte", "B");
addAbbreviation("double", "D");
addAbbreviation("char", "C");
wrapperClassToPrimitiveClassMap.put(Boolean.class, boolean.class);
wrapperClassToPrimitiveClassMap.put(Byte.class, byte.class);
wrapperClassToPrimitiveClassMap.put(Character.class, char.class);
wrapperClassToPrimitiveClassMap.put(Double.class, double.class);
wrapperClassToPrimitiveClassMap.put(Float.class, float.class);
wrapperClassToPrimitiveClassMap.put(Integer.class, int.class);
wrapperClassToPrimitiveClassMap.put(Long.class, long.class);
wrapperClassToPrimitiveClassMap.put(Short.class, short.class);
for (Map.Entry<Class<?>, Class<?>> entry : wrapperClassToPrimitiveClassMap.entrySet()) {
primitiveClassToWrapperClassMap.put(entry.getValue(), entry.getKey());
registerCommonClasses(entry.getKey());
}
Set<Class<?>> primitiveTypes = new HashSet<Class<?>>(32);
primitiveTypes.addAll(wrapperClassToPrimitiveClassMap.values());
primitiveTypes.addAll(Arrays.asList(new Class<?>[] {
boolean[].class, byte[].class, char[].class, double[].class,
float[].class, int[].class, long[].class, short[].class}));
primitiveTypes.add(void.class);
for (Class<?> primitiveType : primitiveTypes) {
primitiveNameToPrimitiveClassMap.put(primitiveType.getName(), primitiveType);
}
registerCommonClasses(Boolean[].class, Byte[].class, Character[].class, Double[].class,
Float[].class, Integer[].class, Long[].class, Short[].class);
registerCommonClasses(Number.class, Number[].class, String.class, String[].class,
Object.class, Object[].class, Class.class, Class[].class);
registerCommonClasses(Throwable.class, Exception.class, RuntimeException.class,
Error.class, StackTraceElement.class, StackTraceElement[].class);
}
/**
* 注册普通类
*
* @param commonClasses
*/
private static void registerCommonClasses(Class<?>... commonClasses) {
for (Class<?> clazz : commonClasses) {
commonClassCache.put(clazz.getName(), clazz);
}
}
/**
* 基本数据类型名转成基本数据类型类
* example: "int" ->"int.class"
* @param name 基本数据类型名 example:"[B", "char"
* @return 基本数据类型类
*/
public static Class<?> convertPrimitiveNameToPrimitiveClass(String primitiveName) {
Class<?> result = null;
// Most class names will be quite long, considering that they
// SHOULD sit in a package, so a length check is worthwhile.
if (primitiveName != null && primitiveName.length() <= 8) {
// Could be a primitive - likely.
result = primitiveNameToPrimitiveClassMap.get(primitiveName);
}
return result;
}
/**
* 基本数据类型转成基本数据类型封装类
* example: "int.class" -> "Integer.class" ,如果失败则"int.class" -> "int.class"
* @param clazz
* @return
*/
public static Class<?> convertPrimitiveClassToWrapperClass(Class<?> clazz) {
Class<?> convertedClass = clazz;
if (clazz != null && clazz.isPrimitive()) {
convertedClass = (Class<?>) primitiveClassToWrapperClassMap.get(clazz);
}
return convertedClass;
}
/**
* 基本数据类型转成基本数据类型封装类(数组方式)
*example: "int.class[]" -> "Integer.class[]"
*
* @param classes
* @return
*/
public static Class<?>[] convertPrimitiveClassesToWrapperClasses(Class<?>[] classes) {
if (classes == null) {
return null;
}
if (classes.length == 0) {
return classes;
}
Class<?>[] convertedClasses = new Class[classes.length];
for (int i = 0; i < classes.length; i++) {
convertedClasses[i] = convertPrimitiveClassToWrapperClass(classes[i]);
}
return convertedClasses;
}
/**
* 基本数据类型封装类转成基本数据类型
*example: "Integer.class" -> "int.class"
*
* @param clazz
* @return
*/
public static Class<?> convertWrapperClassToPrimitiveClass(Class<?> clazz) {
return (Class<?>) wrapperClassToPrimitiveClassMap.get(clazz);
}
/**
* 基本数据类型封装类转成基本数据类型(数组方式)
*example: "Integer.class[]" -> "int.class[]"
*
* @param classes
* @return
*/
public static Class<?>[] convertWrapperClassesToPrimitiveClasses(Class<?>[] classes) {
if (classes == null) {
return null;
}
if (classes.length == 0) {
return classes;
}
Class<?>[] convertedClasses = new Class[classes.length];
for (int i = 0; i < classes.length; i++) {
convertedClasses[i] = convertWrapperClassToPrimitiveClass(classes[i]);
}
return convertedClasses;
}
/**
* 类名集称转换成类集
*example: List<"java.lang.String"> -> List<"String.class">
*
* @param classNames 全限定类名集合
* @return
*/
public static List<Class<?>> convertClassNamesToClasses(List<String> classNames) {
if (classNames == null) {
return null;
}
List<Class<?>> classes = new ArrayList<Class<?>>(classNames.size());
for (Iterator<String> it = classNames.iterator(); it.hasNext();) {
String className = (String) it.next();
try {
classes.add(Class.forName(className));
} catch (Exception ex) {
classes.add(null);
}
}
return classes;
}
/**
* 类转换成类名称
*example: List<"String.class"> -> List<"java.lang.String">
*
* @param classes
* @return
*/
public static List<String> convertClassesToClassNames(List<Class<?>> classes) {
if (classes == null) {
return null;
}
List<String> classNames = new ArrayList<String>(classes.size());
for (Iterator<Class<?>> it = classes.iterator(); it.hasNext();) {
Class<?> clazz = (Class<?>) it.next();
if (clazz == null) {
classNames.add(null);
} else {
classNames.add(clazz.getName());
}
}
return classNames;
}
/**
* 将资源路径"/"转换成类名路径"."
* example: "java/lang/String" -> "java.lang.String"
*
* @param resourcePath
* @return
*/
public static String convertResourcePathToClassName(String resourcePath) {
if (resourcePath == null) {
throw new IllegalArgumentException("Resource path must not be null");
}
return resourcePath.replace('/', '.');
}
/**
* 将类名路径"."转换成资源路径"/"
*example: "java.lang.String" -> "java/lang/String"
*
* @param className
* @return
*/
public static String convertClassNameToResourcePath(String className) {
if (className == null) {
throw new IllegalArgumentException("Class name must not be null");
}
return className.replace('.', '/');
}
/**
* 将类的包名转换成资源路径
*example: "java.lang" -> "java/lang"
*
* @param clazz
* @return
*/
public static String convertClassPackageToResourcePath(Class<?> clazz) {
if (clazz == null) {
return "";
}
String className = clazz.getName();
int packageEndIndex = className.lastIndexOf('.');
if (packageEndIndex == -1) {
return "";
}
String packageName = className.substring(0, packageEndIndex);
return packageName.replace('.', '/');
}
/**
* 将资源路径加到包路径中
*
* @param clazz
* @param resourceName
* @return
*/
public static String addResourcePathToPackagePath(Class<?> clazz, String resourceName) {
if (resourceName == null) {
throw new IllegalArgumentException("Resource name must not be null");
}
if (!resourceName.startsWith("/")) {
return convertClassPackageToResourcePath(clazz) + "/" + resourceName;
}
return convertClassPackageToResourcePath(clazz) + resourceName;
}
/**
* 将类名集转成字符串
*
* @param classes
* @return
*/
public static String convertClassNamesToString(Collection<Class<?>> classes) {
if (classes == null || classes.isEmpty()) {
return "[]";
}
StringBuilder sb = new StringBuilder("[");
for (Iterator<Class<?>> it = classes.iterator(); it.hasNext(); ) {
Class<?> clazz = it.next();
sb.append(clazz.getName());
if (it.hasNext()) {
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
}
/**
* 将类名集转成字符串
*
* @param classes
* @return
*/
public static String convertClassNamesToString(Class<?>... classes) {
return convertClassNamesToString(Arrays.asList(classes));
}
/**
* 将类名集转成类数组
*
* @param collection
* @return
*/
public static Class<?>[] convertClassCollectionToClassArray(Collection<Class<?>> collection) {
if (collection == null) {
return null;
}
return collection.toArray(new Class<?>[collection.size()]);
}
/**
* 获取默认类加载器
*
* @return
*/
public static ClassLoader getDefaultClassLoader() {
ClassLoader cl = null;
try {
cl = Thread.currentThread().getContextClassLoader();
}
catch (Throwable ex) {
// Cannot access thread context ClassLoader - falling back to system class loader...
}
if (cl == null) {
// No thread context class loader -> use class loader of this class.
cl = ClassUtils.class.getClassLoader();
}
return cl;
}
/**
* 用自定义类加载器类加载器复写线程上下文类加载器
*
* @param classLoaderToUse 用户自定义类加载器
* @return
*/
public static ClassLoader overrideThreadContextClassLoader(ClassLoader classLoaderToUse) {
Thread currentThread = Thread.currentThread();
ClassLoader threadContextClassLoader = currentThread.getContextClassLoader();
if (classLoaderToUse != null && !classLoaderToUse.equals(threadContextClassLoader)) {
currentThread.setContextClassLoader(classLoaderToUse);
return threadContextClassLoader;
}
else {
return null;
}
}
/**
* 置换Class.forName()方法,以扩展支持对基本数据类型和数组的类实例化
*
* @param name 类名
* @return
* @throws ClassNotFoundException
* @throws LinkageError
*/
@Deprecated
public static Class<?> forName(String name) throws ClassNotFoundException, LinkageError {
return forName(name, getDefaultClassLoader());
}
/**
* 置换Class.forName()方法,以扩展支持对基本数据类型和数组的类实例化
*
* @param name 类名
* @param classLoader 类加载器
* @return
* @throws ClassNotFoundException
* @throws LinkageError
*/
public static Class<?> forName(String name, ClassLoader classLoader) throws ClassNotFoundException, LinkageError {
if (name == null) {
throw new IllegalArgumentException("Name must not be null");
}
Class<?> clazz = convertPrimitiveNameToPrimitiveClass(name);
if (clazz == null) {
clazz = commonClassCache.get(name);
}
if (clazz != null) {
return clazz;
}
// "java.lang.String[]" style arrays
if (name.endsWith(ARRAY_SUFFIX)) {
String elementClassName = name.substring(0, name.length() - ARRAY_SUFFIX.length());
Class<?> elementClass = forName(elementClassName, classLoader);
return Array.newInstance(elementClass, 0).getClass();
}
// "[Ljava.lang.String;" style arrays
if (name.startsWith(NON_PRIMITIVE_ARRAY_PREFIX) && name.endsWith(";")) {
String elementName = name.substring(NON_PRIMITIVE_ARRAY_PREFIX.length(), name.length() - 1);
Class<?> elementClass = forName(elementName, classLoader);
return Array.newInstance(elementClass, 0).getClass();
}
// "[[I" or "[[Ljava.lang.String;" style arrays
if (name.startsWith(INTERNAL_ARRAY_PREFIX)) {
String elementName = name.substring(INTERNAL_ARRAY_PREFIX.length());
Class<?> elementClass = forName(elementName, classLoader);
return Array.newInstance(elementClass, 0).getClass();
}
ClassLoader classLoaderToUse = classLoader;
if (classLoaderToUse == null) {
classLoaderToUse = getDefaultClassLoader();
}
try {
return classLoaderToUse.loadClass(name);
}
catch (ClassNotFoundException ex) {
int lastDotIndex = name.lastIndexOf('.');
if (lastDotIndex != -1) {
String innerClassName = name.substring(0, lastDotIndex) + '$' + name.substring(lastDotIndex + 1);
try {
return classLoaderToUse.loadClass(innerClassName);
}
catch (ClassNotFoundException ex2) {
// swallow - let original exception get through
}
}
throw ex;
}
}
/**
* 获得新对象
*
* @param clazz 类
* @return
*/
public static Object getNewInstance(Class<?> clazz){
if (clazz == null) {
throw new IllegalArgumentException("clazz must not be null");
}
Object obj = null;
try {
obj = clazz.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
if (obj == null) {
throw new IllegalArgumentException("Error:the new object is null");
}
return obj;
}
/**
* 解析类名(包括基本数据类型和数组)
*
* @param className
* @param classLoader
* @return
* @throws IllegalArgumentException
*/
public static Class<?> resolveClassName(String className, ClassLoader classLoader) throws IllegalArgumentException {
try {
return forName(className, classLoader);
}
catch (ClassNotFoundException ex) {
throw new IllegalArgumentException("Cannot find class [" + className + "]", ex);
}
catch (LinkageError ex) {
throw new IllegalArgumentException(
"Error loading class [" + className + "]: problem with class file or dependent class.", ex);
}
}
/**
* 判断提供的类名是否存在且可以被加载
*
* @param className example:"com.lsl.test.ExceptionTest"
* @return
*/
@Deprecated
public static boolean isPresent(String className) {
return isPresent(className, getDefaultClassLoader());
}
/**
* 判断提供的类名是否存在且可以被加载
*
* @param className example:"com.lsl.test.ExceptionTest"
* @param classLoader
* @return
*/
public static boolean isPresent(String className, ClassLoader classLoader) {
try {
forName(className, classLoader);
return true;
}
catch (Throwable ex) {
// Class or one of its dependencies is not present...
return false;
}
}
/**
* 获取用户自定义类
*
* @param instance
* @return
*/
public static Class<?> getUserClass(Object instance) {
if (instance == null) {
throw new IllegalArgumentException("Instance must not be null");
}
return getUserClass(instance.getClass());
}
/**
* 获取用户自定义类
* 对于被cglib AOP过的对象, 取得真实的Class类型
* @param clazz
* @return
*/
public static Class<?> getUserClass(Class<?> clazz) {
if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) {
Class<?> superClass = clazz.getSuperclass();
if (superClass != null && !Object.class.equals(superClass)) {
return superClass;
}
}
return clazz;
}
/**
* 判断给定的类是否缓存安全
*(是否指定类存在于指定类加载器或其父类加载器)
* @param clazz 给定的类
* @param classLoader 类加载器
* @return
*/
public static boolean isCacheSafe(Class<?> clazz, ClassLoader classLoader) {
if (clazz == null) {
throw new IllegalArgumentException("Class must not be null");
}
ClassLoader target = clazz.getClassLoader();
if (target == null) {
return false;
}
ClassLoader cur = classLoader;
if (cur == target) {
return true;
}
while (cur != null) {
cur = cur.getParent();
if (cur == target) {
return true;
}
}
return false;
}
/**
* 获取类简略名称
*
* @param className
* @return
*/
public static String getShortClassName(String className) {
if(className == null || className.length() == 0){
throw new IllegalArgumentException("Class name must not be empty");
}
int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR);
int nameEndIndex = className.indexOf(CGLIB_CLASS_SEPARATOR);
if (nameEndIndex == -1) {
nameEndIndex = className.length();
}
String shortName = className.substring(lastDotIndex + 1, nameEndIndex);
shortName = shortName.replace(INNER_CLASS_SEPARATOR, PACKAGE_SEPARATOR);
return shortName;
}
/**
* 获取类简略名称
*
* @param clazz
* @return
*/
public static String getShortClassName(Class<?> clazz) {
return getShortClassName(getQualifiedName(clazz));
}
/**
* 获取小写开头的javabean属性格式的字符串对应类的简略名称
*
* @param clazz
* @return
*/
public static String getShortNameAsProperty(Class<?> clazz) {
String shortName = ClassUtils.getShortClassName(clazz);
int dotIndex = shortName.lastIndexOf('.');
shortName = (dotIndex != -1 ? shortName.substring(dotIndex + 1) : shortName);
//获得一个字符串并将它转换成普通 Java 变量名称大写形式的实用工具方法
return Introspector.decapitalize(shortName);
}
/**
* 获取规范类名称(包括数组类)
*
* @param clazz
* @return
*/
public static String getQualifiedName(Class<?> clazz) {
if (clazz == null) {
throw new IllegalArgumentException("Class must not be null");
}
if (clazz.isArray()) {
return getQualifiedNameForArray(clazz);
}
else {
return clazz.getName();
}
}
/**
* 为数组构建一个规范类名
*
* @param clazz
* @return
*/
private static String getQualifiedNameForArray(Class<?> clazz) {
StringBuilder result = new StringBuilder();
while (clazz.isArray()) {
//返回表示数组组件类型的Class
clazz = clazz.getComponentType();
result.append(ClassUtils.ARRAY_SUFFIX);
}
result.insert(0, clazz.getName());
return result.toString();
}
/**
* 获取.class文件名称,格式:"String.class"
*
* @param clazz
* @return
*/
public static String getClassFileName(Class<?> clazz) {
if (clazz == null) {
throw new IllegalArgumentException("Class must not be null");
}
String className = clazz.getName();
int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR);
return className.substring(lastDotIndex + 1) + CLASS_FILE_SUFFIX;
}
/**
* 获取包名,格式:"java.lang"
*
* @param clazz
* @return
*/
public static String getPackageName(Class<?> clazz) {
if (clazz == null) {
throw new IllegalArgumentException("Class must not be null");
}
return getPackageName(clazz.getName());
}
/**
* 获取包名,格式:"java.lang"
*
* @param fqClassName 全限定类名
* @return
*/
public static String getPackageName(String fqClassName) {
if (fqClassName == null) {
throw new IllegalArgumentException("Class name must not be null");
}
int lastDotIndex = fqClassName.lastIndexOf(PACKAGE_SEPARATOR);
return (lastDotIndex != -1 ? fqClassName.substring(0, lastDotIndex) : "");
}
/**
* 获取规范方法名
*
* @param method
* @return
*/
public static String getQualifiedMethodName(Method method) {
if (method == null) {
throw new IllegalArgumentException("Method must not be null");
}
return method.getDeclaringClass().getName() + "." + method.getName();
}
/**
* 获取对象的描述名,通常等同于对象的简略名称,数组则带[]
*
* @param value
* @return
*/
public static String getDescriptiveType(Object value) {
if (value == null) {
return null;
}
Class<?> clazz = value.getClass();
if (Proxy.isProxyClass(clazz)) {
StringBuilder result = new StringBuilder(clazz.getName());
result.append(" implementing ");
Class<?>[] ifcs = clazz.getInterfaces();
for (int i = 0; i < ifcs.length; i++) {
result.append(ifcs[i].getName());
if (i < ifcs.length - 1) {
result.append(',');
}
}
return result.toString();
}
else if (clazz.isArray()) {
return getQualifiedNameForArray(clazz);
}
else {
return clazz.getName();
}
}
/**
* 判断Class是否与用户知道的类名匹配
*
* @param clazz
* @param className
* @return
*/
public static boolean isMatchesClassName(Class<?> clazz, String className) {
return (className != null &&
(className.equals(clazz.getName()) || className.equals(clazz.getSimpleName()) ||
(clazz.isArray() && className.equals(getQualifiedNameForArray(clazz)))));
}
/**
*是否是基本数据类型封装类
*
* @param clazz
* @return
*/
public static boolean isPrimitiveWrapper(Class<?> clazz) {
if (clazz == null) {
throw new IllegalArgumentException("Class must not be null");
}
return wrapperClassToPrimitiveClassMap.containsKey(clazz);
}
/**
* 是否是基本数据类型类或者是其封装类
*
* @param clazz
* @return
*/
public static boolean isPrimitiveOrWrapper(Class<?> clazz) {
if (clazz == null) {
throw new IllegalArgumentException("Class must not be null");
}
return (clazz.isPrimitive() || isPrimitiveWrapper(clazz));
}
/**
* 是否是基本数据类型数组类
*
* @param clazz
* @return
*/
public static boolean isPrimitiveArray(Class<?> clazz) {
if (clazz == null) {
throw new IllegalArgumentException("Class must not be null");
}
return (clazz.isArray() && clazz.getComponentType().isPrimitive());
}
/**
* 是否是基本数据类型封装类数组类
*
* @param clazz
* @return
*/
public static boolean isPrimitiveWrapperArray(Class<?> clazz) {
if (clazz == null) {
throw new IllegalArgumentException("Class must not be null");
}
return (clazz.isArray() && isPrimitiveWrapper(clazz.getComponentType()));
}
/**
* 源类是否可以分配给目标类(包括基本数据类型),即目标类(toClass)是源类(clazz)的父类或接口,或两者一样
*
* @param clazz 源 类
* @param toClass 目标类
* @param autoboxing true表示自动装箱/自动拆箱
* @return
*/
public static boolean isAssignable(Class<?> clazz, Class<?> toClazz, boolean autoboxing) {
if (toClazz == null) {
return false;
}
// have to check for null, as isAssignableFrom doesn't
if (clazz == null) {
return !(toClazz.isPrimitive());
}
//自动装箱/自动拆箱:
if (autoboxing) {
if (clazz.isPrimitive() && !toClazz.isPrimitive()) {
clazz = convertPrimitiveClassToWrapperClass(clazz);
if (clazz == null) {
return false;
}
}
if (toClazz.isPrimitive() && !clazz.isPrimitive()) {
clazz = convertWrapperClassToPrimitiveClass(clazz);
if (clazz == null) {
return false;
}
}
}
if (clazz.equals(toClazz)) {
return true;
}
if (clazz.isPrimitive()) {
if (toClazz.isPrimitive() == false) {
return false;
}
if (Integer.TYPE.equals(clazz)) {
return Long.TYPE.equals(toClazz)
|| Float.TYPE.equals(toClazz)
|| Double.TYPE.equals(toClazz);
}
if (Long.TYPE.equals(clazz)) {
return Float.TYPE.equals(toClazz)
|| Double.TYPE.equals(toClazz);
}
if (Boolean.TYPE.equals(clazz)) {
return false;
}
if (Double.TYPE.equals(clazz)) {
return false;
}
if (Float.TYPE.equals(clazz)) {
return Double.TYPE.equals(toClazz);
}
if (Character.TYPE.equals(clazz)) {
return Integer.TYPE.equals(toClazz)
|| Long.TYPE.equals(toClazz)
|| Float.TYPE.equals(toClazz)
|| Double.TYPE.equals(toClazz);
}
if (Short.TYPE.equals(clazz)) {
return Integer.TYPE.equals(toClazz)
|| Long.TYPE.equals(toClazz)
|| Float.TYPE.equals(toClazz)
|| Double.TYPE.equals(toClazz);
}
if (Byte.TYPE.equals(clazz)) {
return Short.TYPE.equals(toClazz)
|| Integer.TYPE.equals(toClazz)
|| Long.TYPE.equals(toClazz)
|| Float.TYPE.equals(toClazz)
|| Double.TYPE.equals(toClazz);
}
// should never get here
return false;
}
return toClazz.isAssignableFrom(clazz);
}
/**
* 源类是否可以分配给目标(包括基本数据类型,不自动装箱或拆箱),即目标类(toClass)是源类(clazz)的父类或接口,或两者一样
*
* @param clazz 源 类
* @param toClass 目标类
* @return
*/
public static boolean isAssignable(Class<?> clazz, Class<?> toClazz) {
return isAssignable(clazz, toClazz, false);
}
/**
* 源类数组是否可以分配给目标类数组(包括基本数据类型)
*
* @param classArray 源类数组
* @param toClassArray 目标类数组
* @param autoboxing true表示自动装箱/自动拆箱
* @return
*/
public static boolean isAssignable(Class<?>[] classArray, Class<?>[] toClassArray, boolean autoboxing) {
if ((classArray == null && toClassArray != null && toClassArray.length > 0) ||
(toClassArray == null && classArray != null && classArray.length > 0) ||
(classArray != null && toClassArray != null && classArray.length != toClassArray.length)) {
return false;
}
if (classArray == null) {
classArray = new Class[0];
}
if (toClassArray == null) {
toClassArray = new Class[0];
}
for (int i = 0; i < classArray.length; i++) {
if (isAssignable(classArray[i], toClassArray[i], autoboxing) == false) {
return false;
}
}
return true;
}
/**
* 源类数组是否可以分配给目标类数组
*
* @param classArray 源类数组
* @param toClassArray 目标类数组
* @return
*/
public static boolean isAssignable(Class<?>[] classArray, Class<?>[] toClassArray) {
return isAssignable(classArray, toClassArray, false);
}
/**
* 右边的值是否可分配给左边的类型
*
* @param type 左边的类型
* @param value 右边的值
* @return
*/
public static boolean isAssignableValue(Class<?> type, Object value) {
if (type == null) {
throw new IllegalArgumentException("Type must not be null");
}
return (value != null ? isAssignable(value.getClass(), type) : !type.isPrimitive());
}
/**
* 是否是内部类或者是静态嵌套类
*
* @param clazz
* @return
*/
public static boolean isInnerClass(Class<?> clazz) {
if (clazz == null) {
return false;
}
return clazz.getName().indexOf(INNER_CLASS_SEPARATOR) >= 0;
}
/**
* 获取类的所有接口(包括父类的接口)
*
* @param clazz
* @return
*/
public static List<Class<?>> getInterfacesOfClassAsList(Class<?> clazz) {
if (clazz == null) {
throw new IllegalArgumentException("Class must not be null");
}
List<Class<?>> interfacesFound = new ArrayList<Class<?>>();
getInterfacesOfClassAsList(clazz, interfacesFound);
return interfacesFound;
}
/**
* 获取类的所有接口(包括父类),返回List格式
*
* @param clazz
* @param interfacesFound 存放获取的结果
*/
private static void getInterfacesOfClassAsList(Class<?> clazz, List<Class<?>> interfacesFound) {
while (clazz != null) {
Class<?>[] interfaces = clazz.getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
if (!interfacesFound.contains(interfaces[i])) {
interfacesFound.add(interfaces[i]);
getInterfacesOfClassAsList(interfaces[i], interfacesFound);
}
}
clazz = clazz.getSuperclass();
}
}
/**
* 获取对象的所有接口(包括父类),返回数组格式
*
* @param instance
* @return 类数组
*/
public static Class<?>[] getInterfacesOfInstanceAsArray (Object instance) {
if (instance == null) {
throw new IllegalArgumentException("Instance must not be null");
}
return getInterfacesOfClassInClassLoaderAsArray(instance.getClass());
}
/**
* 获取类的所有接口(包括父类),返回数组格式
*
* @param clazz
* @return 类数组
*/
public static Class<?>[] getInterfacesOfClassInClassLoaderAsArray(Class<?> clazz) {
return getInterfacesOfClassInClassLoaderAsArray(clazz, null);
}
/**
* 获取类的所有在指定类加载器中可见的接口(包括父类),返回数组格式
*
* @param clazz
* @param classLoader
* @return 类数组
*/
public static Class<?>[] getInterfacesOfClassInClassLoaderAsArray(Class<?> clazz, ClassLoader classLoader) {
Set<Class> ifcs = getInterfacesOfClassInClassLoaderAsSet(clazz, classLoader);
return ifcs.toArray(new Class[ifcs.size()]);
}
/**
* 获取对象所有的接口类(返回类集合形式)
*
* @param instance
* @return 类的Set集合
*/
public static Set<Class> getInterfacesOfInstanceAsSet(Object instance) {
if (instance == null) {
throw new IllegalArgumentException("Instance must not be null");
}
return getInterfacesOfClassInClassLoaderAsSet(instance.getClass());
}
/**
* 获取类的所有接口类(包括父类),返回Set格式
*
* @param clazz
* @return
*/
public static Set<Class> getInterfacesOfClassInClassLoaderAsSet(Class clazz) {
return getInterfacesOfClassInClassLoaderAsSet(clazz, null);
}
/**
* 获取类的所有在指定类加载器中可见的接口(包括父类),返回Set格式
*
* @param clazz 类
* @param classLoader 类加载器
* @return
*/
public static Set<Class> getInterfacesOfClassInClassLoaderAsSet(Class clazz, ClassLoader classLoader) {
if (clazz == null) {
throw new IllegalArgumentException("Class must not be null");
}
if (clazz.isInterface() && isClassVisibleInClassLoader(clazz, classLoader)) {
//static T set<T> singleton(T o)方法返回一个只包含指定对象的不可变 set
return Collections.singleton(clazz);
}
Set<Class> interfaces = new LinkedHashSet<Class>();
while (clazz != null) {
Class<?>[] ifcs = clazz.getInterfaces();
for (Class<?> ifc : ifcs) {
interfaces.addAll(getInterfacesOfClassInClassLoaderAsSet(ifc, classLoader));
}
clazz = clazz.getSuperclass();
}
return interfaces;
}
/**
* 获取指定类的所有父类
*
* @param clazz
* @return
*/
public static List<Class<?>> getAllSuperclasses(Class<?> clazz) {
if (clazz == null) {
throw new IllegalArgumentException("Class must not be null");
}
List<Class<?>> clazzes = new ArrayList<Class<?>>();
Class<?> superclass = clazz.getSuperclass();
while (superclass != null) {
clazzes.add(superclass);
superclass = superclass.getSuperclass();
}
return clazzes;
}
/**
* 是否指定的类在类加载器中可见
*
* @param clazz
* @param classLoader
* @return
*/
public static boolean isClassVisibleInClassLoader(Class<?> clazz, ClassLoader classLoader) {
if (classLoader == null) {
return true;
}
try {
Class<?> actualClass = classLoader.loadClass(clazz.getName());
return (clazz == actualClass);
// Else: different interface class found...
}
catch (ClassNotFoundException ex) {
// No interface class found...
return false;
}
}
/**
* 获取多个接口的代理类
*
* @param interfaces 类口数组类
* @param classLoader 类加载器
* @return
*/
public static Class<?> getProxyClassByInterfaces(Class<?>[] interfaces, ClassLoader classLoader) {
if (interfaces == null || interfaces.length == 0) {
throw new IllegalArgumentException("Interfaces must not be empty");
}
if (classLoader == null) {
throw new IllegalArgumentException("ClassLoader must not be null");
}
return Proxy.getProxyClass(classLoader, interfaces);
}
/**
* 是否是CGLIB代理对象
*
* @param object
* @return
*/
public static boolean isCglibProxy(Object object) {
return ClassUtils.isCglibProxyClass(object.getClass());
}
/**
* 是否是CGLIB代理类
*
* @param clazz
* @return
*/
public static boolean isCglibProxyClass(Class<?> clazz) {
return (clazz != null && isCglibProxyClassName(clazz.getName()));
}
/**
* 是否是CGLIB代理类名(即类名中包括“$$”字符)
*
* @param className 全限定类名
* @return
*/
public static boolean isCglibProxyClassName(String className) {
return (className != null && className.contains(CGLIB_CLASS_SEPARATOR));
}
/**
* 获取类名简写
*
* @param object
* @param valueIfNull
* @return
*/
public static String getShortCanonicalName(Object object, String valueIfNull) {
if (object == null) {
return valueIfNull;
}
return getShortCanonicalName(object.getClass().getName());
}
/**
* 获取类名简写
*
* @param cls
* @return
*/
public static String getShortCanonicalName(Class<?> clazz) {
if (clazz == null) {
return "";
}
return getShortCanonicalName(clazz.getName());
}
/**
* 获取类名简写
*
* @param canonicalName
* @return
*/
public static String getShortCanonicalName(String canonicalName) {
return ClassUtils.getShortClassName(getCanonicalName(canonicalName));
}
/**
* 获取包名
*
* @param object
* @param valueIfNull
* @return
*/
public static String getPackageCanonicalName(Object object, String valueIfNull) {
if (object == null) {
return valueIfNull;
}
return getPackageCanonicalName(object.getClass().getName());
}
/**
* 获取包名
*
* @param clazz
* @return
*/
public static String getPackageCanonicalName(Class<?> clazz) {
if (clazz == null) {
return "";
}
return getPackageCanonicalName(clazz.getName());
}
/**
* 获取包名
*
* @param canonicalName
* @return
*/
public static String getPackageCanonicalName(String canonicalName) {
return ClassUtils.getPackageName(getCanonicalName(canonicalName));
}
/**
* 将类名转成规范的JLS格式名
*
* @param className
* @return
*/
public static String toCanonicalName(String className) {
className = deleteWhitespace(className);
if (className == null) {
throw new IllegalArgumentException("className must not be null or only white space");
} else if (className.endsWith("[]")) {
StringBuilder classNameBuffer = new StringBuilder();
while (className.endsWith("[]")) {
className = className.substring(0, className.length() - 2);
classNameBuffer.append("[");
}
String abbreviation = (String) abbreviationMap.get(className);
if (abbreviation != null) {
classNameBuffer.append(abbreviation);
} else {
classNameBuffer.append("L").append(className).append(";");
}
className = classNameBuffer.toString();
}
return className;
}
/**
* 将规范的JLS格式名转换成类名
*
* @param className
* @return
*/
private static String getCanonicalName(String className) {
className = deleteWhitespace(className);
if (className == null) {
return null;
} else {
int dim = 0;
while (className.startsWith("[")) {
dim++;
className = className.substring(1);
}
if (dim < 1) {
return className;
} else {
if (className.startsWith("L")) {
className = className.substring(1, className.endsWith(";") ? className.length() - 1 : className.length());
} else {
if (className.length() > 0) {
className = (String) reverseAbbreviationMap.get(className.substring(0, 1));
}
}
StringBuilder canonicalClassNameBuffer = new StringBuilder(className);
for (int i = 0; i < dim; i++) {
canonicalClassNameBuffer.append("[]");
}
return canonicalClassNameBuffer.toString();
}
}
}
/**
* 删除字符串中的空白符
*
* @param str
* @return
*/
private static String deleteWhitespace(String str) {
if (str == null || str.length() == 0) {
return str;
}
int sz = str.length();
char[] chs = new char[sz];
int count = 0;
for (int i = 0; i < sz; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
chs[count++] = str.charAt(i);
}
}
if (count == sz) {
return str;
}
return new String(chs, 0, count);
}
/**
*
* @param args
*/
public static void main(String[] args) {
System.out.println(ClassUtils.isPresent("com.lsl.test.ExceptionTest"));
System.out.println(ClassUtils.getShortClassName("com.lsl.Test3"));
System.out.println(ClassUtils.getDefaultClassLoader());
System.out.println(ClassUtils.getCanonicalName(ClassUtils.toCanonicalName("com.lsl.core.exception.NestedRuntimeException[]")));
}
}