首页

关于apache的common-lang实现ClassUtils工具类对获取Class类的简称、包名及父类集合、类转换、获取依赖关系类集等操作

标签:ClassUtils,类工具类,apache,commons-lang,反射reflect     发布时间:2018-02-10   

一、前言

apachecommons-lang开源包中org.apache.commons.lang3.ClassUtils类工具类,对类的简称getShortClassName或getSimpleName、获取所在包名称getPackageName、获取所有父亲类集合getAllSuperclasses、获取所有接口getAllInterfaces、字符串集合到类集合转换convertClassNamesToClasses、是否原始类判断isPrimitiveOrWrapper、是否内部类判断isInnerClass、通过类加载器获取class对象getClass、获取Public方法getPublicMethod、获取依赖集hierarchy等操作方法。

二、源码说明

1.ClassUtils

package org.apache.commons.lang3;@b@@b@import java.lang.reflect.Method;@b@import java.lang.reflect.Modifier;@b@import java.util.ArrayList;@b@import java.util.Collections;@b@import java.util.HashMap;@b@import java.util.HashSet;@b@import java.util.Iterator;@b@import java.util.LinkedHashSet;@b@import java.util.List;@b@import java.util.Map;@b@import java.util.Map.Entry;@b@import java.util.Set;@b@import org.apache.commons.lang3.mutable.MutableObject;@b@@b@public class ClassUtils@b@{@b@  public static final char PACKAGE_SEPARATOR_CHAR = 46;@b@  public static final String PACKAGE_SEPARATOR = String.valueOf('.');@b@  public static final char INNER_CLASS_SEPARATOR_CHAR = 36;@b@  public static final String INNER_CLASS_SEPARATOR = String.valueOf('$');@b@  private static final Map<Class<?>, Class<?>> primitiveWrapperMap = new HashMap();@b@  private static final Map<Class<?>, Class<?>> wrapperPrimitiveMap;@b@  private static final Map<String, String> abbreviationMap;@b@  private static final Map<String, String> reverseAbbreviationMap;@b@@b@  public static String getShortClassName(Object object, String valueIfNull)@b@  {@b@    if (object == null)@b@      return valueIfNull;@b@@b@    return getShortClassName(object.getClass());@b@  }@b@@b@  public static String getShortClassName(Class<?> cls)@b@  {@b@    if (cls == null)@b@      return "";@b@@b@    return getShortClassName(cls.getName());@b@  }@b@@b@  public static String getShortClassName(String className)@b@  {@b@    if (StringUtils.isEmpty(className)) {@b@      return "";@b@    }@b@@b@    StringBuilder arrayPrefix = new StringBuilder();@b@@b@    if (className.startsWith("[")) {@b@      while (className.charAt(0) == '[') {@b@        className = className.substring(1);@b@        arrayPrefix.append("[]");@b@      }@b@@b@      if ((className.charAt(0) == 'L') && (className.charAt(className.length() - 1) == ';')) {@b@        className = className.substring(1, className.length() - 1);@b@      }@b@@b@      if (reverseAbbreviationMap.containsKey(className))@b@        className = (String)reverseAbbreviationMap.get(className);@b@@b@    }@b@@b@    int lastDotIdx = className.lastIndexOf(46);@b@    int innerIdx = className.indexOf(36, (lastDotIdx == -1) ? 0 : lastDotIdx + 1);@b@@b@    String out = className.substring(lastDotIdx + 1);@b@    if (innerIdx != -1)@b@      out = out.replace('$', '.');@b@@b@    return new StringBuilder().append(out).append(arrayPrefix).toString();@b@  }@b@@b@  public static String getSimpleName(Class<?> cls)@b@  {@b@    if (cls == null)@b@      return "";@b@@b@    return cls.getSimpleName();@b@  }@b@@b@  public static String getSimpleName(Object object, String valueIfNull)@b@  {@b@    if (object == null)@b@      return valueIfNull;@b@@b@    return getSimpleName(object.getClass());@b@  }@b@@b@  public static String getPackageName(Object object, String valueIfNull)@b@  {@b@    if (object == null)@b@      return valueIfNull;@b@@b@    return getPackageName(object.getClass());@b@  }@b@@b@  public static String getPackageName(Class<?> cls)@b@  {@b@    if (cls == null)@b@      return "";@b@@b@    return getPackageName(cls.getName());@b@  }@b@@b@  public static String getPackageName(String className)@b@  {@b@    if (StringUtils.isEmpty(className)) {@b@      return "";@b@    }@b@@b@    while (className.charAt(0) == '[') {@b@      className = className.substring(1);@b@    }@b@@b@    if ((className.charAt(0) == 'L') && (className.charAt(className.length() - 1) == ';')) {@b@      className = className.substring(1);@b@    }@b@@b@    int i = className.lastIndexOf(46);@b@    if (i == -1)@b@      return "";@b@@b@    return className.substring(0, i);@b@  }@b@@b@  public static List<Class<?>> getAllSuperclasses(Class<?> cls)@b@  {@b@    if (cls == null)@b@      return null;@b@@b@    List classes = new ArrayList();@b@    Class superclass = cls.getSuperclass();@b@    while (superclass != null) {@b@      classes.add(superclass);@b@      superclass = superclass.getSuperclass();@b@    }@b@    return classes;@b@  }@b@@b@  public static List<Class<?>> getAllInterfaces(Class<?> cls)@b@  {@b@    if (cls == null) {@b@      return null;@b@    }@b@@b@    LinkedHashSet interfacesFound = new LinkedHashSet();@b@    getAllInterfaces(cls, interfacesFound);@b@@b@    return new ArrayList(interfacesFound);@b@  }@b@@b@  private static void getAllInterfaces(Class<?> cls, HashSet<Class<?>> interfacesFound)@b@  {@b@    while (cls != null) {@b@      Class[] interfaces = cls.getInterfaces();@b@@b@      Class[] arr$ = interfaces; int len$ = arr$.length; for (int i$ = 0; i$ < len$; ++i$) { Class i = arr$[i$];@b@        if (interfacesFound.add(i))@b@          getAllInterfaces(i, interfacesFound);@b@@b@      }@b@@b@      cls = cls.getSuperclass();@b@    }@b@  }@b@@b@  public static List<Class<?>> convertClassNamesToClasses(List<String> classNames)@b@  {@b@    if (classNames == null)@b@      return null;@b@@b@    List classes = new ArrayList(classNames.size());@b@    for (String className : classNames)@b@      try {@b@        classes.add(Class.forName(className));@b@      } catch (Exception ex) {@b@        classes.add(null);@b@      }@b@@b@    return classes;@b@  }@b@@b@  public static List<String> convertClassesToClassNames(List<Class<?>> classes)@b@  {@b@    if (classes == null)@b@      return null;@b@@b@    List classNames = new ArrayList(classes.size());@b@    for (Class cls : classes)@b@      if (cls == null)@b@        classNames.add(null);@b@      else@b@        classNames.add(cls.getName());@b@@b@@b@    return classNames;@b@  }@b@@b@  public static boolean isAssignable(Class<?>[] classArray, Class<?>[] toClassArray)@b@  {@b@    return isAssignable(classArray, toClassArray, SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_5));@b@  }@b@@b@  public static boolean isAssignable(Class<?>[] classArray, Class<?>[] toClassArray, boolean autoboxing)@b@  {@b@    if (!(ArrayUtils.isSameLength(classArray, toClassArray)))@b@      return false;@b@@b@    if (classArray == null)@b@      classArray = ArrayUtils.EMPTY_CLASS_ARRAY;@b@@b@    if (toClassArray == null)@b@      toClassArray = ArrayUtils.EMPTY_CLASS_ARRAY;@b@@b@    for (int i = 0; i < classArray.length; ++i)@b@      if (!(isAssignable(classArray[i], toClassArray[i], autoboxing)))@b@        return false;@b@@b@@b@    return true;@b@  }@b@@b@  public static boolean isPrimitiveOrWrapper(Class<?> type)@b@  {@b@    if (type == null)@b@      return false;@b@@b@    return ((type.isPrimitive()) || (isPrimitiveWrapper(type)));@b@  }@b@@b@  public static boolean isPrimitiveWrapper(Class<?> type)@b@  {@b@    return wrapperPrimitiveMap.containsKey(type);@b@  }@b@@b@  public static boolean isAssignable(Class<?> cls, Class<?> toClass)@b@  {@b@    return isAssignable(cls, toClass, SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_5));@b@  }@b@@b@  public static boolean isAssignable(Class<?> cls, Class<?> toClass, boolean autoboxing)@b@  {@b@    if (toClass == null) {@b@      return false;@b@    }@b@@b@    if (cls == null) {@b@      return (!(toClass.isPrimitive()));@b@    }@b@@b@    if (autoboxing) {@b@      if ((cls.isPrimitive()) && (!(toClass.isPrimitive()))) {@b@        cls = primitiveToWrapper(cls);@b@        if (cls == null)@b@          return false;@b@      }@b@@b@      if ((toClass.isPrimitive()) && (!(cls.isPrimitive()))) {@b@        cls = wrapperToPrimitive(cls);@b@        if (cls == null)@b@          return false;@b@      }@b@    }@b@@b@    if (cls.equals(toClass))@b@      return true;@b@@b@    if (cls.isPrimitive()) {@b@      if (!(toClass.isPrimitive()))@b@        return false;@b@@b@      if (Integer.TYPE.equals(cls)) {@b@        return ((Long.TYPE.equals(toClass)) || (Float.TYPE.equals(toClass)) || (Double.TYPE.equals(toClass)));@b@      }@b@@b@      if (Long.TYPE.equals(cls)) {@b@        return ((Float.TYPE.equals(toClass)) || (Double.TYPE.equals(toClass)));@b@      }@b@@b@      if (Boolean.TYPE.equals(cls))@b@        return false;@b@@b@      if (Double.TYPE.equals(cls))@b@        return false;@b@@b@      if (Float.TYPE.equals(cls))@b@        return Double.TYPE.equals(toClass);@b@@b@      if (Character.TYPE.equals(cls)) {@b@        return ((Integer.TYPE.equals(toClass)) || (Long.TYPE.equals(toClass)) || (Float.TYPE.equals(toClass)) || (Double.TYPE.equals(toClass)));@b@      }@b@@b@      if (Short.TYPE.equals(cls)) {@b@        return ((Integer.TYPE.equals(toClass)) || (Long.TYPE.equals(toClass)) || (Float.TYPE.equals(toClass)) || (Double.TYPE.equals(toClass)));@b@      }@b@@b@      if (Byte.TYPE.equals(cls)) {@b@        return ((Short.TYPE.equals(toClass)) || (Integer.TYPE.equals(toClass)) || (Long.TYPE.equals(toClass)) || (Float.TYPE.equals(toClass)) || (Double.TYPE.equals(toClass)));@b@      }@b@@b@      return false;@b@    }@b@    return toClass.isAssignableFrom(cls);@b@  }@b@@b@  public static Class<?> primitiveToWrapper(Class<?> cls)@b@  {@b@    Class convertedClass = cls;@b@    if ((cls != null) && (cls.isPrimitive()))@b@      convertedClass = (Class)primitiveWrapperMap.get(cls);@b@@b@    return convertedClass;@b@  }@b@@b@  public static Class<?>[] primitivesToWrappers(Class<?>[] classes)@b@  {@b@    if (classes == null) {@b@      return null;@b@    }@b@@b@    if (classes.length == 0) {@b@      return classes;@b@    }@b@@b@    Class[] convertedClasses = new Class[classes.length];@b@    for (int i = 0; i < classes.length; ++i)@b@      convertedClasses[i] = primitiveToWrapper(classes[i]);@b@@b@    return convertedClasses;@b@  }@b@@b@  public static Class<?> wrapperToPrimitive(Class<?> cls)@b@  {@b@    return ((Class)wrapperPrimitiveMap.get(cls));@b@  }@b@@b@  public static Class<?>[] wrappersToPrimitives(Class<?>[] classes)@b@  {@b@    if (classes == null) {@b@      return null;@b@    }@b@@b@    if (classes.length == 0) {@b@      return classes;@b@    }@b@@b@    Class[] convertedClasses = new Class[classes.length];@b@    for (int i = 0; i < classes.length; ++i)@b@      convertedClasses[i] = wrapperToPrimitive(classes[i]);@b@@b@    return convertedClasses;@b@  }@b@@b@  public static boolean isInnerClass(Class<?> cls)@b@  {@b@    return ((cls != null) && (cls.getEnclosingClass() != null));@b@  }@b@@b@  public static Class<?> getClass(ClassLoader classLoader, String className, boolean initialize)@b@    throws ClassNotFoundException@b@  {@b@    try@b@    {@b@      Class clazz;@b@      if (abbreviationMap.containsKey(className)) {@b@        String clsName = new StringBuilder().append("[").append((String)abbreviationMap.get(className)).toString();@b@        clazz = Class.forName(clsName, initialize, classLoader).getComponentType();@b@      } else {@b@        clazz = Class.forName(toCanonicalName(className), initialize, classLoader);@b@      }@b@      return clazz;@b@    }@b@    catch (ClassNotFoundException ex) {@b@      int lastDotIndex = className.lastIndexOf(46);@b@@b@      if (lastDotIndex != -1);@b@      try {@b@        return getClass(classLoader, new StringBuilder().append(className.substring(0, lastDotIndex)).append('$').append(className.substring(lastDotIndex + 1)).toString(), initialize);@b@      }@b@      catch (ClassNotFoundException ex2)@b@      {@b@        throw ex;@b@      }@b@    }@b@  }@b@@b@  public static Class<?> getClass(ClassLoader classLoader, String className)@b@    throws ClassNotFoundException@b@  {@b@    return getClass(classLoader, className, true);@b@  }@b@@b@  public static Class<?> getClass(String className)@b@    throws ClassNotFoundException@b@  {@b@    return getClass(className, true);@b@  }@b@@b@  public static Class<?> getClass(String className, boolean initialize)@b@    throws ClassNotFoundException@b@  {@b@    ClassLoader contextCL = Thread.currentThread().getContextClassLoader();@b@    ClassLoader loader = (contextCL == null) ? ClassUtils.class.getClassLoader() : contextCL;@b@    return getClass(loader, className, initialize);@b@  }@b@@b@  public static Method getPublicMethod(Class<?> cls, String methodName, Class<?>[] parameterTypes)@b@    throws SecurityException, NoSuchMethodException@b@  {@b@    Method declaredMethod = cls.getMethod(methodName, parameterTypes);@b@    if (Modifier.isPublic(declaredMethod.getDeclaringClass().getModifiers())) {@b@      return declaredMethod;@b@    }@b@@b@    List candidateClasses = new ArrayList();@b@    candidateClasses.addAll(getAllInterfaces(cls));@b@    candidateClasses.addAll(getAllSuperclasses(cls));@b@@b@    Iterator i$ = candidateClasses.iterator();@b@    while (true) { label64: Class candidateClass;@b@      Method candidateMethod;@b@      while (true) { if (!(i$.hasNext())) break label137; candidateClass = (Class)i$.next();@b@        if (Modifier.isPublic(candidateClass.getModifiers()))@b@          break;@b@      }@b@      try@b@      {@b@        candidateMethod = candidateClass.getMethod(methodName, parameterTypes);@b@      } catch (NoSuchMethodException ex) {@b@        break label64:@b@      }@b@      if (Modifier.isPublic(candidateMethod.getDeclaringClass().getModifiers()))@b@        return candidateMethod;@b@@b@    }@b@@b@    label137: throw new NoSuchMethodException(new StringBuilder().append("Can't find a public method for ").append(methodName).append(" ").append(ArrayUtils.toString(parameterTypes)).toString());@b@  }@b@@b@  private static String toCanonicalName(String className)@b@  {@b@    className = StringUtils.deleteWhitespace(className);@b@    if (className == null)@b@      throw new NullPointerException("className must not be null.");@b@    if (className.endsWith("[]")) {@b@      StringBuilder classNameBuffer = new StringBuilder();@b@      while (className.endsWith("[]")) {@b@        className = className.substring(0, className.length() - 2);@b@        classNameBuffer.append("[");@b@      }@b@      String abbreviation = (String)abbreviationMap.get(className);@b@      if (abbreviation != null)@b@        classNameBuffer.append(abbreviation);@b@      else@b@        classNameBuffer.append("L").append(className).append(";");@b@@b@      className = classNameBuffer.toString();@b@    }@b@    return className;@b@  }@b@@b@  public static Class<?>[] toClass(Object[] array)@b@  {@b@    if (array == null)@b@      return null;@b@    if (array.length == 0)@b@      return ArrayUtils.EMPTY_CLASS_ARRAY;@b@@b@    Class[] classes = new Class[array.length];@b@    for (int i = 0; i < array.length; ++i)@b@      classes[i] = ((array[i] == null) ? null : array[i].getClass());@b@@b@    return classes;@b@  }@b@@b@  public static String getShortCanonicalName(Object object, String valueIfNull)@b@  {@b@    if (object == null)@b@      return valueIfNull;@b@@b@    return getShortCanonicalName(object.getClass().getName());@b@  }@b@@b@  public static String getShortCanonicalName(Class<?> cls)@b@  {@b@    if (cls == null)@b@      return "";@b@@b@    return getShortCanonicalName(cls.getName());@b@  }@b@@b@  public static String getShortCanonicalName(String canonicalName)@b@  {@b@    return getShortClassName(getCanonicalName(canonicalName));@b@  }@b@@b@  public static String getPackageCanonicalName(Object object, String valueIfNull)@b@  {@b@    if (object == null)@b@      return valueIfNull;@b@@b@    return getPackageCanonicalName(object.getClass().getName());@b@  }@b@@b@  public static String getPackageCanonicalName(Class<?> cls)@b@  {@b@    if (cls == null)@b@      return "";@b@@b@    return getPackageCanonicalName(cls.getName());@b@  }@b@@b@  public static String getPackageCanonicalName(String canonicalName)@b@  {@b@    return getPackageName(getCanonicalName(canonicalName));@b@  }@b@@b@  private static String getCanonicalName(String className)@b@  {@b@    className = StringUtils.deleteWhitespace(className);@b@    if (className == null)@b@      return null;@b@@b@    int dim = 0;@b@    while (className.startsWith("[")) {@b@      ++dim;@b@      className = className.substring(1);@b@    }@b@    if (dim < 1)@b@      return className;@b@@b@    if (className.startsWith("L")) {@b@      className = className.substring(1, (className.endsWith(";")) ? className.length() - 1 : className.length());@b@    }@b@    else if (className.length() > 0) {@b@      className = (String)reverseAbbreviationMap.get(className.substring(0, 1));@b@    }@b@@b@    StringBuilder canonicalClassNameBuffer = new StringBuilder(className);@b@    for (int i = 0; i < dim; ++i)@b@      canonicalClassNameBuffer.append("[]");@b@@b@    return canonicalClassNameBuffer.toString();@b@  }@b@@b@  public static Iterable<Class<?>> hierarchy(Class<?> type)@b@  {@b@    return hierarchy(type, Interfaces.EXCLUDE);@b@  }@b@@b@  public static Iterable<Class<?>> hierarchy(Class<?> type, Interfaces interfacesBehavior)@b@  {@b@    Iterable classes = new Iterable(type)@b@    {@b@      public Iterator<Class<?>> iterator()@b@      {@b@        MutableObject next = new MutableObject(this.val$type);@b@        return new Iterator(this, next)@b@        {@b@          public boolean hasNext()@b@          {@b@            return (this.val$next.getValue() != null);@b@          }@b@@b@          public Class<?> next()@b@          {@b@            Class result = (Class)this.val$next.getValue();@b@            this.val$next.setValue(result.getSuperclass());@b@            return result;@b@          }@b@@b@          public void remove()@b@          {@b@            throw new UnsupportedOperationException();@b@          }@b@@b@        };@b@      }@b@@b@    };@b@    if (interfacesBehavior != Interfaces.INCLUDE)@b@      return classes;@b@@b@    return new Iterable(classes)@b@    {@b@      public Iterator<Class<?>> iterator()@b@      {@b@        Set seenInterfaces = new HashSet();@b@        Iterator wrapped = this.val$classes.iterator();@b@@b@        return new Iterator(this, wrapped, seenInterfaces)@b@        {@b@          Iterator<Class<?>> interfaces;@b@@b@          public boolean hasNext() {@b@            return ((this.interfaces.hasNext()) || (this.val$wrapped.hasNext()));@b@          }@b@@b@          public Class<?> next()@b@          {@b@            if (this.interfaces.hasNext()) {@b@              Class nextInterface = (Class)this.interfaces.next();@b@              this.val$seenInterfaces.add(nextInterface);@b@              return nextInterface;@b@            }@b@            Class nextSuperclass = (Class)this.val$wrapped.next();@b@            Set currentInterfaces = new LinkedHashSet();@b@            walkInterfaces(currentInterfaces, nextSuperclass);@b@            this.interfaces = currentInterfaces.iterator();@b@            return nextSuperclass;@b@          }@b@@b@          private void walkInterfaces(, Class<?> c) {@b@            Class[] arr$ = c.getInterfaces(); int len$ = arr$.length; for (int i$ = 0; i$ < len$; ++i$) { Class iface = arr$[i$];@b@              if (!(this.val$seenInterfaces.contains(iface)))@b@                addTo.add(iface);@b@@b@              walkInterfaces(addTo, iface);@b@            }@b@          }@b@@b@          public void remove()@b@          {@b@            throw new UnsupportedOperationException();@b@          }@b@        };@b@      }@b@    };@b@  }@b@@b@  static@b@  {@b@    primitiveWrapperMap.put(Boolean.TYPE, Boolean.class);@b@    primitiveWrapperMap.put(Byte.TYPE, Byte.class);@b@    primitiveWrapperMap.put(Character.TYPE, Character.class);@b@    primitiveWrapperMap.put(Short.TYPE, Short.class);@b@    primitiveWrapperMap.put(Integer.TYPE, Integer.class);@b@    primitiveWrapperMap.put(Long.TYPE, Long.class);@b@    primitiveWrapperMap.put(Double.TYPE, Double.class);@b@    primitiveWrapperMap.put(Float.TYPE, Float.class);@b@    primitiveWrapperMap.put(Void.TYPE, Void.TYPE);@b@@b@    wrapperPrimitiveMap = new HashMap();@b@@b@    for (Class primitiveClass : primitiveWrapperMap.keySet()) {@b@      Class wrapperClass = (Class)primitiveWrapperMap.get(primitiveClass);@b@      if (!(primitiveClass.equals(wrapperClass))) {@b@        wrapperPrimitiveMap.put(wrapperClass, primitiveClass);@b@      }@b@@b@    }@b@@b@    Map m = new HashMap();@b@    m.put("int", "I");@b@    m.put("boolean", "Z");@b@    m.put("float", "F");@b@    m.put("long", "J");@b@    m.put("short", "S");@b@    m.put("byte", "B");@b@    m.put("double", "D");@b@    m.put("char", "C");@b@    m.put("void", "V");@b@    Map r = new HashMap();@b@    for (Map.Entry e : m.entrySet())@b@      r.put(e.getValue(), e.getKey());@b@@b@    abbreviationMap = Collections.unmodifiableMap(m);@b@    reverseAbbreviationMap = Collections.unmodifiableMap(r);@b@  }@b@@b@  public static enum Interfaces@b@  {@b@    INCLUDE, EXCLUDE;@b@  }@b@}

2.MutableObject

package org.apache.commons.lang3.mutable;@b@@b@import java.io.Serializable;@b@@b@public class MutableObject<T>@b@  implements Mutable<T>, Serializable@b@{@b@  private static final long serialVersionUID = 86241875189L;@b@  private T value;@b@@b@  public MutableObject()@b@  {@b@  }@b@@b@  public MutableObject(T value)@b@  {@b@    this.value = value;@b@  }@b@@b@  public T getValue()@b@  {@b@    return this.value;@b@  }@b@@b@  public void setValue(T value)@b@  {@b@    this.value = value;@b@  }@b@@b@  public boolean equals(Object obj)@b@  {@b@    if (obj == null)@b@      return false;@b@@b@    if (this == obj)@b@      return true;@b@@b@    if (super.getClass() == obj.getClass()) {@b@      MutableObject that = (MutableObject)obj;@b@      return this.value.equals(that.value);@b@    }@b@    return false;@b@  }@b@@b@  public int hashCode()@b@  {@b@    return ((this.value == null) ? 0 : this.value.hashCode());@b@  }@b@@b@  public String toString()@b@  {@b@    return ((this.value == null) ? "null" : this.value.toString());@b@  }@b@}