ClassUtils.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.lang3;

  18. import java.lang.reflect.Method;
  19. import java.lang.reflect.Modifier;
  20. import java.util.ArrayList;
  21. import java.util.Arrays;
  22. import java.util.Collections;
  23. import java.util.Comparator;
  24. import java.util.HashMap;
  25. import java.util.HashSet;
  26. import java.util.Iterator;
  27. import java.util.LinkedHashSet;
  28. import java.util.List;
  29. import java.util.Map;
  30. import java.util.Objects;
  31. import java.util.Set;
  32. import java.util.stream.Collectors;

  33. import org.apache.commons.lang3.mutable.MutableObject;

  34. /**
  35.  * Operates on classes without using reflection.
  36.  *
  37.  * <p>
  38.  * This class handles invalid {@code null} inputs as best it can. Each method documents its behavior in more detail.
  39.  * </p>
  40.  *
  41.  * <p>
  42.  * The notion of a {@code canonical name} includes the human readable name for the type, for example {@code int[]}. The
  43.  * non-canonical method variants work with the JVM names, such as {@code [I}.
  44.  * </p>
  45.  *
  46.  * @since 2.0
  47.  */
  48. public class ClassUtils {

  49.     /**
  50.      * Inclusivity literals for {@link #hierarchy(Class, Interfaces)}.
  51.      *
  52.      * @since 3.2
  53.      */
  54.     public enum Interfaces {

  55.         /** Includes interfaces. */
  56.         INCLUDE,

  57.         /** Excludes interfaces. */
  58.         EXCLUDE
  59.     }

  60.     private static final Comparator<Class<?>> COMPARATOR = (o1, o2) -> Objects.compare(getName(o1), getName(o2), String::compareTo);

  61.     /**
  62.      * The package separator character: {@code '&#x2e;' == {@value}}.
  63.      */
  64.     public static final char PACKAGE_SEPARATOR_CHAR = '.';

  65.     /**
  66.      * The package separator String: {@code "&#x2e;"}.
  67.      */
  68.     public static final String PACKAGE_SEPARATOR = String.valueOf(PACKAGE_SEPARATOR_CHAR);

  69.     /**
  70.      * The inner class separator character: {@code '$' == {@value}}.
  71.      */
  72.     public static final char INNER_CLASS_SEPARATOR_CHAR = '$';

  73.     /**
  74.      * The inner class separator String: {@code "$"}.
  75.      */
  76.     public static final String INNER_CLASS_SEPARATOR = String.valueOf(INNER_CLASS_SEPARATOR_CHAR);

  77.     /**
  78.      * Maps names of primitives to their corresponding primitive {@link Class}es.
  79.      */
  80.     private static final Map<String, Class<?>> namePrimitiveMap = new HashMap<>();

  81.     static {
  82.         namePrimitiveMap.put(Boolean.TYPE.getSimpleName(), Boolean.TYPE);
  83.         namePrimitiveMap.put(Byte.TYPE.getSimpleName(), Byte.TYPE);
  84.         namePrimitiveMap.put(Character.TYPE.getSimpleName(), Character.TYPE);
  85.         namePrimitiveMap.put(Double.TYPE.getSimpleName(), Double.TYPE);
  86.         namePrimitiveMap.put(Float.TYPE.getSimpleName(), Float.TYPE);
  87.         namePrimitiveMap.put(Integer.TYPE.getSimpleName(), Integer.TYPE);
  88.         namePrimitiveMap.put(Long.TYPE.getSimpleName(), Long.TYPE);
  89.         namePrimitiveMap.put(Short.TYPE.getSimpleName(), Short.TYPE);
  90.         namePrimitiveMap.put(Void.TYPE.getSimpleName(), Void.TYPE);
  91.     }

  92.     /**
  93.      * Maps primitive {@link Class}es to their corresponding wrapper {@link Class}.
  94.      */
  95.     private static final Map<Class<?>, Class<?>> primitiveWrapperMap = new HashMap<>();

  96.     static {
  97.         primitiveWrapperMap.put(Boolean.TYPE, Boolean.class);
  98.         primitiveWrapperMap.put(Byte.TYPE, Byte.class);
  99.         primitiveWrapperMap.put(Character.TYPE, Character.class);
  100.         primitiveWrapperMap.put(Short.TYPE, Short.class);
  101.         primitiveWrapperMap.put(Integer.TYPE, Integer.class);
  102.         primitiveWrapperMap.put(Long.TYPE, Long.class);
  103.         primitiveWrapperMap.put(Double.TYPE, Double.class);
  104.         primitiveWrapperMap.put(Float.TYPE, Float.class);
  105.         primitiveWrapperMap.put(Void.TYPE, Void.TYPE);
  106.     }

  107.     /**
  108.      * Maps wrapper {@link Class}es to their corresponding primitive types.
  109.      */
  110.     private static final Map<Class<?>, Class<?>> wrapperPrimitiveMap = new HashMap<>();

  111.     static {
  112.         primitiveWrapperMap.forEach((primitiveClass, wrapperClass) -> {
  113.             if (!primitiveClass.equals(wrapperClass)) {
  114.                 wrapperPrimitiveMap.put(wrapperClass, primitiveClass);
  115.             }
  116.         });
  117.     }

  118.     /**
  119.      * Maps a primitive class name to its corresponding abbreviation used in array class names.
  120.      */
  121.     private static final Map<String, String> abbreviationMap;

  122.     /**
  123.      * Maps an abbreviation used in array class names to corresponding primitive class name.
  124.      */
  125.     private static final Map<String, String> reverseAbbreviationMap;

  126.     /** Feed abbreviation maps. */
  127.     static {
  128.         final Map<String, String> map = new HashMap<>();
  129.         map.put("int", "I");
  130.         map.put("boolean", "Z");
  131.         map.put("float", "F");
  132.         map.put("long", "J");
  133.         map.put("short", "S");
  134.         map.put("byte", "B");
  135.         map.put("double", "D");
  136.         map.put("char", "C");
  137.         abbreviationMap = Collections.unmodifiableMap(map);
  138.         reverseAbbreviationMap = Collections.unmodifiableMap(map.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey)));
  139.     }

  140.     /**
  141.      * Gets the class comparator, comparing by class name.
  142.      *
  143.      * @return the class comparator.
  144.      * @since 3.13.0
  145.      */
  146.     public static Comparator<Class<?>> comparator() {
  147.         return COMPARATOR;
  148.     }

  149.     /**
  150.      * Given a {@link List} of {@link Class} objects, this method converts them into class names.
  151.      *
  152.      * <p>
  153.      * A new {@link List} is returned. {@code null} objects will be copied into the returned list as {@code null}.
  154.      * </p>
  155.      *
  156.      * @param classes the classes to change
  157.      * @return a {@link List} of class names corresponding to the Class objects, {@code null} if null input
  158.      * @throws ClassCastException if {@code classes} contains a non-{@link Class} entry
  159.      */
  160.     public static List<String> convertClassesToClassNames(final List<Class<?>> classes) {
  161.         return classes == null ? null : classes.stream().map(e -> getName(e, null)).collect(Collectors.toList());
  162.     }

  163.     /**
  164.      * Given a {@link List} of class names, this method converts them into classes.
  165.      *
  166.      * <p>
  167.      * A new {@link List} is returned. If the class name cannot be found, {@code null} is stored in the {@link List}. If the
  168.      * class name in the {@link List} is {@code null}, {@code null} is stored in the output {@link List}.
  169.      * </p>
  170.      *
  171.      * @param classNames the classNames to change
  172.      * @return a {@link List} of Class objects corresponding to the class names, {@code null} if null input
  173.      * @throws ClassCastException if classNames contains a non String entry
  174.      */
  175.     public static List<Class<?>> convertClassNamesToClasses(final List<String> classNames) {
  176.         if (classNames == null) {
  177.             return null;
  178.         }
  179.         final List<Class<?>> classes = new ArrayList<>(classNames.size());
  180.         classNames.forEach(className -> {
  181.             try {
  182.                 classes.add(Class.forName(className));
  183.             } catch (final Exception ex) {
  184.                 classes.add(null);
  185.             }
  186.         });
  187.         return classes;
  188.     }

  189.     /**
  190.      * Gets the abbreviated name of a {@link Class}.
  191.      *
  192.      * @param cls the class to get the abbreviated name for, may be {@code null}
  193.      * @param lengthHint the desired length of the abbreviated name
  194.      * @return the abbreviated name or an empty string
  195.      * @throws IllegalArgumentException if len &lt;= 0
  196.      * @see #getAbbreviatedName(String, int)
  197.      * @since 3.4
  198.      */
  199.     public static String getAbbreviatedName(final Class<?> cls, final int lengthHint) {
  200.         if (cls == null) {
  201.             return StringUtils.EMPTY;
  202.         }
  203.         return getAbbreviatedName(cls.getName(), lengthHint);
  204.     }

  205.     /**
  206.      * Gets the abbreviated class name from a {@link String}.
  207.      *
  208.      * <p>
  209.      * The string passed in is assumed to be a class name - it is not checked.
  210.      * </p>
  211.      *
  212.      * <p>
  213.      * The abbreviation algorithm will shorten the class name, usually without significant loss of meaning.
  214.      * </p>
  215.      *
  216.      * <p>
  217.      * The abbreviated class name will always include the complete package hierarchy. If enough space is available,
  218.      * rightmost sub-packages will be displayed in full length. The abbreviated package names will be shortened to a single
  219.      * character.
  220.      * </p>
  221.      * <p>
  222.      * Only package names are shortened, the class simple name remains untouched. (See examples.)
  223.      * </p>
  224.      * <p>
  225.      * The result will be longer than the desired length only if all the package names shortened to a single character plus
  226.      * the class simple name with the separating dots together are longer than the desired length. In other words, when the
  227.      * class name cannot be shortened to the desired length.
  228.      * </p>
  229.      * <p>
  230.      * If the class name can be shortened then the final length will be at most {@code lengthHint} characters.
  231.      * </p>
  232.      * <p>
  233.      * If the {@code lengthHint} is zero or negative then the method throws exception. If you want to achieve the shortest
  234.      * possible version then use {@code 1} as a {@code lengthHint}.
  235.      * </p>
  236.      *
  237.      * <table>
  238.      * <caption>Examples</caption>
  239.      * <tr>
  240.      * <td>className</td>
  241.      * <td>len</td>
  242.      * <td>return</td>
  243.      * </tr>
  244.      * <tr>
  245.      * <td>null</td>
  246.      * <td>1</td>
  247.      * <td>""</td>
  248.      * </tr>
  249.      * <tr>
  250.      * <td>"java.lang.String"</td>
  251.      * <td>5</td>
  252.      * <td>"j.l.String"</td>
  253.      * </tr>
  254.      * <tr>
  255.      * <td>"java.lang.String"</td>
  256.      * <td>15</td>
  257.      * <td>"j.lang.String"</td>
  258.      * </tr>
  259.      * <tr>
  260.      * <td>"java.lang.String"</td>
  261.      * <td>30</td>
  262.      * <td>"java.lang.String"</td>
  263.      * </tr>
  264.      * <tr>
  265.      * <td>"org.apache.commons.lang3.ClassUtils"</td>
  266.      * <td>18</td>
  267.      * <td>"o.a.c.l.ClassUtils"</td>
  268.      * </tr>
  269.      * </table>
  270.      *
  271.      * @param className the className to get the abbreviated name for, may be {@code null}
  272.      * @param lengthHint the desired length of the abbreviated name
  273.      * @return the abbreviated name or an empty string if the specified class name is {@code null} or empty string. The
  274.      *         abbreviated name may be longer than the desired length if it cannot be abbreviated to the desired length.
  275.      * @throws IllegalArgumentException if {@code len <= 0}
  276.      * @since 3.4
  277.      */
  278.     public static String getAbbreviatedName(final String className, final int lengthHint) {
  279.         if (lengthHint <= 0) {
  280.             throw new IllegalArgumentException("len must be > 0");
  281.         }
  282.         if (className == null) {
  283.             return StringUtils.EMPTY;
  284.         }
  285.         if (className.length() <= lengthHint) {
  286.             return className;
  287.         }
  288.         final char[] abbreviated = className.toCharArray();
  289.         int target = 0;
  290.         int source = 0;
  291.         while (source < abbreviated.length) {
  292.             // copy the next part
  293.             int runAheadTarget = target;
  294.             while (source < abbreviated.length && abbreviated[source] != '.') {
  295.                 abbreviated[runAheadTarget++] = abbreviated[source++];
  296.             }

  297.             ++target;
  298.             if (useFull(runAheadTarget, source, abbreviated.length, lengthHint) || target > runAheadTarget) {
  299.                 target = runAheadTarget;
  300.             }

  301.             // copy the '.' unless it was the last part
  302.             if (source < abbreviated.length) {
  303.                 abbreviated[target++] = abbreviated[source++];
  304.             }
  305.         }
  306.         return new String(abbreviated, 0, target);
  307.     }

  308.     /**
  309.      * Gets a {@link List} of all interfaces implemented by the given class and its superclasses.
  310.      *
  311.      * <p>
  312.      * The order is determined by looking through each interface in turn as declared in the source file and following its
  313.      * hierarchy up. Then each superclass is considered in the same way. Later duplicates are ignored, so the order is
  314.      * maintained.
  315.      * </p>
  316.      *
  317.      * @param cls the class to look up, may be {@code null}
  318.      * @return the {@link List} of interfaces in order, {@code null} if null input
  319.      */
  320.     public static List<Class<?>> getAllInterfaces(final Class<?> cls) {
  321.         if (cls == null) {
  322.             return null;
  323.         }

  324.         final LinkedHashSet<Class<?>> interfacesFound = new LinkedHashSet<>();
  325.         getAllInterfaces(cls, interfacesFound);

  326.         return new ArrayList<>(interfacesFound);
  327.     }

  328.     /**
  329.      * Gets the interfaces for the specified class.
  330.      *
  331.      * @param cls the class to look up, may be {@code null}
  332.      * @param interfacesFound the {@link Set} of interfaces for the class
  333.      */
  334.     private static void getAllInterfaces(Class<?> cls, final HashSet<Class<?>> interfacesFound) {
  335.         while (cls != null) {
  336.             final Class<?>[] interfaces = cls.getInterfaces();

  337.             for (final Class<?> i : interfaces) {
  338.                 if (interfacesFound.add(i)) {
  339.                     getAllInterfaces(i, interfacesFound);
  340.                 }
  341.             }

  342.             cls = cls.getSuperclass();
  343.         }
  344.     }

  345.     /**
  346.      * Gets a {@link List} of superclasses for the given class.
  347.      *
  348.      * @param cls the class to look up, may be {@code null}
  349.      * @return the {@link List} of superclasses in order going up from this one {@code null} if null input
  350.      */
  351.     public static List<Class<?>> getAllSuperclasses(final Class<?> cls) {
  352.         if (cls == null) {
  353.             return null;
  354.         }
  355.         final List<Class<?>> classes = new ArrayList<>();
  356.         Class<?> superclass = cls.getSuperclass();
  357.         while (superclass != null) {
  358.             classes.add(superclass);
  359.             superclass = superclass.getSuperclass();
  360.         }
  361.         return classes;
  362.     }

  363.     /**
  364.      * Gets the canonical class name for a {@link Class}.
  365.      *
  366.      * @param cls the class for which to get the canonical class name; may be null
  367.      * @return the canonical name of the class, or the empty String
  368.      * @since 3.7
  369.      * @see Class#getCanonicalName()
  370.      */
  371.     public static String getCanonicalName(final Class<?> cls) {
  372.         return getCanonicalName(cls, StringUtils.EMPTY);
  373.     }

  374.     /**
  375.      * Gets the canonical name for a {@link Class}.
  376.      *
  377.      * @param cls the class for which to get the canonical class name; may be null
  378.      * @param valueIfNull the return value if null
  379.      * @return the canonical name of the class, or {@code valueIfNull}
  380.      * @since 3.7
  381.      * @see Class#getCanonicalName()
  382.      */
  383.     public static String getCanonicalName(final Class<?> cls, final String valueIfNull) {
  384.         if (cls == null) {
  385.             return valueIfNull;
  386.         }
  387.         final String canonicalName = cls.getCanonicalName();
  388.         return canonicalName == null ? valueIfNull : canonicalName;
  389.     }

  390.     /**
  391.      * Gets the canonical name for an {@link Object}.
  392.      *
  393.      * @param object the object for which to get the canonical class name; may be null
  394.      * @return the canonical name of the object, or the empty String
  395.      * @since 3.7
  396.      * @see Class#getCanonicalName()
  397.      */
  398.     public static String getCanonicalName(final Object object) {
  399.         return getCanonicalName(object, StringUtils.EMPTY);
  400.     }

  401.     /**
  402.      * Gets the canonical name for an {@link Object}.
  403.      *
  404.      * @param object the object for which to get the canonical class name; may be null
  405.      * @param valueIfNull the return value if null
  406.      * @return the canonical name of the object or {@code valueIfNull}
  407.      * @since 3.7
  408.      * @see Class#getCanonicalName()
  409.      */
  410.     public static String getCanonicalName(final Object object, final String valueIfNull) {
  411.         if (object == null) {
  412.             return valueIfNull;
  413.         }
  414.         final String canonicalName = object.getClass().getCanonicalName();
  415.         return canonicalName == null ? valueIfNull : canonicalName;
  416.     }

  417.     /**
  418.      * Converts a given name of class into canonical format. If name of class is not a name of array class it returns
  419.      * unchanged name.
  420.      *
  421.      * <p>
  422.      * The method does not change the {@code $} separators in case the class is inner class.
  423.      * </p>
  424.      *
  425.      * <p>
  426.      * Example:
  427.      * <ul>
  428.      * <li>{@code getCanonicalName("[I") = "int[]"}</li>
  429.      * <li>{@code getCanonicalName("[Ljava.lang.String;") = "java.lang.String[]"}</li>
  430.      * <li>{@code getCanonicalName("java.lang.String") = "java.lang.String"}</li>
  431.      * </ul>
  432.      * </p>
  433.      *
  434.      * @param className the name of class
  435.      * @return canonical form of class name
  436.      * @since 2.4
  437.      */
  438.     private static String getCanonicalName(String className) {
  439.         className = StringUtils.deleteWhitespace(className);
  440.         if (className == null) {
  441.             return null;
  442.         }
  443.         int dim = 0;
  444.         while (className.startsWith("[")) {
  445.             dim++;
  446.             className = className.substring(1);
  447.         }
  448.         if (dim < 1) {
  449.             return className;
  450.         }
  451.         if (className.startsWith("L")) {
  452.             className = className.substring(1, className.endsWith(";") ? className.length() - 1 : className.length());
  453.         } else if (!className.isEmpty()) {
  454.             className = reverseAbbreviationMap.get(className.substring(0, 1));
  455.         }
  456.         final StringBuilder canonicalClassNameBuffer = new StringBuilder(className);
  457.         for (int i = 0; i < dim; i++) {
  458.             canonicalClassNameBuffer.append("[]");
  459.         }
  460.         return canonicalClassNameBuffer.toString();
  461.     }

  462.     /**
  463.      * Returns the (initialized) class represented by {@code className} using the {@code classLoader}. This implementation
  464.      * supports the syntaxes "{@code java.util.Map.Entry[]}", "{@code java.util.Map$Entry[]}",
  465.      * "{@code [Ljava.util.Map.Entry;}", and "{@code [Ljava.util.Map$Entry;}".
  466.      *
  467.      * @param classLoader the class loader to use to load the class
  468.      * @param className the class name
  469.      * @return the class represented by {@code className} using the {@code classLoader}
  470.      * @throws NullPointerException if the className is null
  471.      * @throws ClassNotFoundException if the class is not found
  472.      */
  473.     public static Class<?> getClass(final ClassLoader classLoader, final String className) throws ClassNotFoundException {
  474.         return getClass(classLoader, className, true);
  475.     }

  476.     /**
  477.      * Returns the class represented by {@code className} using the {@code classLoader}. This implementation supports the
  478.      * syntaxes "{@code java.util.Map.Entry[]}", "{@code java.util.Map$Entry[]}", "{@code [Ljava.util.Map.Entry;}", and
  479.      * "{@code [Ljava.util.Map$Entry;}".
  480.      *
  481.      * @param classLoader the class loader to use to load the class
  482.      * @param className the class name
  483.      * @param initialize whether the class must be initialized
  484.      * @return the class represented by {@code className} using the {@code classLoader}
  485.      * @throws NullPointerException if the className is null
  486.      * @throws ClassNotFoundException if the class is not found
  487.      */
  488.     public static Class<?> getClass(final ClassLoader classLoader, final String className, final boolean initialize) throws ClassNotFoundException {
  489.         try {
  490.             final Class<?> clazz = getPrimitiveClass(className);
  491.             return clazz != null ? clazz : Class.forName(toCanonicalName(className), initialize, classLoader);
  492.         } catch (final ClassNotFoundException ex) {
  493.             // allow path separators (.) as inner class name separators
  494.             final int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);

  495.             if (lastDotIndex != -1) {
  496.                 try {
  497.                     return getClass(classLoader, className.substring(0, lastDotIndex) + INNER_CLASS_SEPARATOR_CHAR + className.substring(lastDotIndex + 1),
  498.                         initialize);
  499.                 } catch (final ClassNotFoundException ignored) {
  500.                     // ignore exception
  501.                 }
  502.             }

  503.             throw ex;
  504.         }
  505.     }

  506.     /**
  507.      * Returns the (initialized) class represented by {@code className} using the current thread's context class loader.
  508.      * This implementation supports the syntaxes "{@code java.util.Map.Entry[]}", "{@code java.util.Map$Entry[]}",
  509.      * "{@code [Ljava.util.Map.Entry;}", and "{@code [Ljava.util.Map$Entry;}".
  510.      *
  511.      * @param className the class name
  512.      * @return the class represented by {@code className} using the current thread's context class loader
  513.      * @throws NullPointerException if the className is null
  514.      * @throws ClassNotFoundException if the class is not found
  515.      */
  516.     public static Class<?> getClass(final String className) throws ClassNotFoundException {
  517.         return getClass(className, true);
  518.     }

  519.     /**
  520.      * Returns the class represented by {@code className} using the current thread's context class loader. This
  521.      * implementation supports the syntaxes "{@code java.util.Map.Entry[]}", "{@code java.util.Map$Entry[]}",
  522.      * "{@code [Ljava.util.Map.Entry;}", and "{@code [Ljava.util.Map$Entry;}".
  523.      *
  524.      * @param className the class name
  525.      * @param initialize whether the class must be initialized
  526.      * @return the class represented by {@code className} using the current thread's context class loader
  527.      * @throws NullPointerException if the className is null
  528.      * @throws ClassNotFoundException if the class is not found
  529.      */
  530.     public static Class<?> getClass(final String className, final boolean initialize) throws ClassNotFoundException {
  531.         final ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
  532.         final ClassLoader loader = contextCL == null ? ClassUtils.class.getClassLoader() : contextCL;
  533.         return getClass(loader, className, initialize);
  534.     }

  535.     /**
  536.      * Delegates to {@link Class#getComponentType()} using generics.
  537.      *
  538.      * @param <T> The array class type.
  539.      * @param cls A class or null.
  540.      * @return The array component type or null.
  541.      * @see Class#getComponentType()
  542.      * @since 3.13.0
  543.      */
  544.     @SuppressWarnings("unchecked")
  545.     public static <T> Class<T> getComponentType(final Class<T[]> cls) {
  546.         return cls == null ? null : (Class<T>) cls.getComponentType();
  547.     }

  548.     /**
  549.      * Null-safe version of {@code cls.getName()}
  550.      *
  551.      * @param cls the class for which to get the class name; may be null
  552.      * @return the class name or the empty string in case the argument is {@code null}
  553.      * @since 3.7
  554.      * @see Class#getSimpleName()
  555.      */
  556.     public static String getName(final Class<?> cls) {
  557.         return getName(cls, StringUtils.EMPTY);
  558.     }

  559.     /**
  560.      * Null-safe version of {@code cls.getName()}
  561.      *
  562.      * @param cls the class for which to get the class name; may be null
  563.      * @param valueIfNull the return value if the argument {@code cls} is {@code null}
  564.      * @return the class name or {@code valueIfNull}
  565.      * @since 3.7
  566.      * @see Class#getName()
  567.      */
  568.     public static String getName(final Class<?> cls, final String valueIfNull) {
  569.         return cls == null ? valueIfNull : cls.getName();
  570.     }

  571.     /**
  572.      * Null-safe version of {@code object.getClass().getName()}
  573.      *
  574.      * @param object the object for which to get the class name; may be null
  575.      * @return the class name or the empty String
  576.      * @since 3.7
  577.      * @see Class#getSimpleName()
  578.      */
  579.     public static String getName(final Object object) {
  580.         return getName(object, StringUtils.EMPTY);
  581.     }

  582.     /**
  583.      * Null-safe version of {@code object.getClass().getSimpleName()}
  584.      *
  585.      * @param object the object for which to get the class name; may be null
  586.      * @param valueIfNull the value to return if {@code object} is {@code null}
  587.      * @return the class name or {@code valueIfNull}
  588.      * @since 3.0
  589.      * @see Class#getName()
  590.      */
  591.     public static String getName(final Object object, final String valueIfNull) {
  592.         return object == null ? valueIfNull : object.getClass().getName();
  593.     }

  594.     /**
  595.      * Gets the package name from the canonical name of a {@link Class}.
  596.      *
  597.      * @param cls the class to get the package name for, may be {@code null}.
  598.      * @return the package name or an empty string
  599.      * @since 2.4
  600.      */
  601.     public static String getPackageCanonicalName(final Class<?> cls) {
  602.         if (cls == null) {
  603.             return StringUtils.EMPTY;
  604.         }
  605.         return getPackageCanonicalName(cls.getName());
  606.     }

  607.     /**
  608.      * Gets the package name from the class name of an {@link Object}.
  609.      *
  610.      * @param object the class to get the package name for, may be null
  611.      * @param valueIfNull the value to return if null
  612.      * @return the package name of the object, or the null value
  613.      * @since 2.4
  614.      */
  615.     public static String getPackageCanonicalName(final Object object, final String valueIfNull) {
  616.         if (object == null) {
  617.             return valueIfNull;
  618.         }
  619.         return getPackageCanonicalName(object.getClass().getName());
  620.     }

  621.     /**
  622.      * Gets the package name from the class name.
  623.      *
  624.      * <p>
  625.      * The string passed in is assumed to be a class name - it is not checked.
  626.      * </p>
  627.      * <p>
  628.      * If the class is in the default package, return an empty string.
  629.      * </p>
  630.      *
  631.      * @param name the name to get the package name for, may be {@code null}
  632.      * @return the package name or an empty string
  633.      * @since 2.4
  634.      */
  635.     public static String getPackageCanonicalName(final String name) {
  636.         return getPackageName(getCanonicalName(name));
  637.     }

  638.     /**
  639.      * Gets the package name of a {@link Class}.
  640.      *
  641.      * @param cls the class to get the package name for, may be {@code null}.
  642.      * @return the package name or an empty string
  643.      */
  644.     public static String getPackageName(final Class<?> cls) {
  645.         if (cls == null) {
  646.             return StringUtils.EMPTY;
  647.         }
  648.         return getPackageName(cls.getName());
  649.     }

  650.     /**
  651.      * Gets the package name of an {@link Object}.
  652.      *
  653.      * @param object the class to get the package name for, may be null
  654.      * @param valueIfNull the value to return if null
  655.      * @return the package name of the object, or the null value
  656.      */
  657.     public static String getPackageName(final Object object, final String valueIfNull) {
  658.         if (object == null) {
  659.             return valueIfNull;
  660.         }
  661.         return getPackageName(object.getClass());
  662.     }

  663.     /**
  664.      * Gets the package name from a {@link String}.
  665.      *
  666.      * <p>
  667.      * The string passed in is assumed to be a class name - it is not checked.
  668.      * </p>
  669.      * <p>
  670.      * If the class is unpackaged, return an empty string.
  671.      * </p>
  672.      *
  673.      * @param className the className to get the package name for, may be {@code null}
  674.      * @return the package name or an empty string
  675.      */
  676.     public static String getPackageName(String className) {
  677.         if (StringUtils.isEmpty(className)) {
  678.             return StringUtils.EMPTY;
  679.         }

  680.         // Strip array encoding
  681.         while (className.charAt(0) == '[') {
  682.             className = className.substring(1);
  683.         }
  684.         // Strip Object type encoding
  685.         if (className.charAt(0) == 'L' && className.charAt(className.length() - 1) == ';') {
  686.             className = className.substring(1);
  687.         }

  688.         final int i = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
  689.         if (i == -1) {
  690.             return StringUtils.EMPTY;
  691.         }
  692.         return className.substring(0, i);
  693.     }

  694.     /**
  695.      * Gets the primitive class for the given class name, for example "byte".
  696.      *
  697.      * @param className the primitive class for the given class name.
  698.      * @return the primitive class.
  699.      */
  700.     static Class<?> getPrimitiveClass(final String className) {
  701.         return namePrimitiveMap.get(className);
  702.     }

  703.     /**
  704.      * Returns the desired Method much like {@code Class.getMethod}, however it ensures that the returned Method is from a
  705.      * public class or interface and not from an anonymous inner class. This means that the Method is invokable and doesn't
  706.      * fall foul of Java bug <a href="https://bugs.java.com/bugdatabase/view_bug.do?bug_id=4071957">4071957</a>).
  707.      *
  708.      * <pre>
  709.      *  {@code Set set = Collections.unmodifiableSet(...);
  710.      *  Method method = ClassUtils.getPublicMethod(set.getClass(), "isEmpty",  new Class[0]);
  711.      *  Object result = method.invoke(set, new Object[]);}
  712.      * </pre>
  713.      *
  714.      * @param cls the class to check, not null
  715.      * @param methodName the name of the method
  716.      * @param parameterTypes the list of parameters
  717.      * @return the method
  718.      * @throws NullPointerException if the class is null
  719.      * @throws SecurityException if a security violation occurred
  720.      * @throws NoSuchMethodException if the method is not found in the given class or if the method doesn't conform with the
  721.      *         requirements
  722.      */
  723.     public static Method getPublicMethod(final Class<?> cls, final String methodName, final Class<?>... parameterTypes) throws NoSuchMethodException {

  724.         final Method declaredMethod = cls.getMethod(methodName, parameterTypes);
  725.         if (isPublic(declaredMethod.getDeclaringClass())) {
  726.             return declaredMethod;
  727.         }

  728.         final List<Class<?>> candidateClasses = new ArrayList<>(getAllInterfaces(cls));
  729.         candidateClasses.addAll(getAllSuperclasses(cls));

  730.         for (final Class<?> candidateClass : candidateClasses) {
  731.             if (!isPublic(candidateClass)) {
  732.                 continue;
  733.             }
  734.             final Method candidateMethod;
  735.             try {
  736.                 candidateMethod = candidateClass.getMethod(methodName, parameterTypes);
  737.             } catch (final NoSuchMethodException ex) {
  738.                 continue;
  739.             }
  740.             if (Modifier.isPublic(candidateMethod.getDeclaringClass().getModifiers())) {
  741.                 return candidateMethod;
  742.             }
  743.         }

  744.         throw new NoSuchMethodException("Can't find a public method for " + methodName + " " + ArrayUtils.toString(parameterTypes));
  745.     }

  746.     /**
  747.      * Gets the canonical name minus the package name from a {@link Class}.
  748.      *
  749.      * @param cls the class for which to get the short canonical class name; may be null
  750.      * @return the canonical name without the package name or an empty string
  751.      * @since 2.4
  752.      * @see Class#getCanonicalName()
  753.      */
  754.     public static String getShortCanonicalName(final Class<?> cls) {
  755.         return cls == null ? StringUtils.EMPTY : getShortCanonicalName(cls.getCanonicalName());
  756.     }

  757.     /**
  758.      * Gets the canonical name minus the package name for an {@link Object}.
  759.      *
  760.      * @param object the class to get the short name for, may be null
  761.      * @param valueIfNull the value to return if null
  762.      * @return the canonical name of the object without the package name, or the null value
  763.      * @since 2.4
  764.      * @see Class#getCanonicalName()
  765.      */
  766.     public static String getShortCanonicalName(final Object object, final String valueIfNull) {
  767.         return object == null ? valueIfNull : getShortCanonicalName(object.getClass().getCanonicalName());
  768.     }

  769.     /**
  770.      * Gets the canonical name minus the package name from a String.
  771.      *
  772.      * <p>
  773.      * The string passed in is assumed to be a class name - it is not checked.
  774.      * </p>
  775.      *
  776.      * <p>
  777.      * Note that this method is mainly designed to handle the arrays and primitives properly. If the class is an inner class
  778.      * then the result value will not contain the outer classes. This way the behavior of this method is different from
  779.      * {@link #getShortClassName(String)}. The argument in that case is class name and not canonical name and the return
  780.      * value retains the outer classes.
  781.      * </p>
  782.      *
  783.      * <p>
  784.      * Note that there is no way to reliably identify the part of the string representing the package hierarchy and the part
  785.      * that is the outer class or classes in case of an inner class. Trying to find the class would require reflective call
  786.      * and the class itself may not even be on the class path. Relying on the fact that class names start with capital
  787.      * letter and packages with lower case is heuristic.
  788.      * </p>
  789.      *
  790.      * <p>
  791.      * It is recommended to use {@link #getShortClassName(String)} for cases when the class is an inner class and use this
  792.      * method for cases it is designed for.
  793.      * </p>
  794.      *
  795.      * <table>
  796.      * <caption>Examples</caption>
  797.      * <tr>
  798.      * <td>return value</td>
  799.      * <td>input</td>
  800.      * </tr>
  801.      * <tr>
  802.      * <td>{@code ""}</td>
  803.      * <td>{@code (String)null}</td>
  804.      * </tr>
  805.      * <tr>
  806.      * <td>{@code "Map.Entry"}</td>
  807.      * <td>{@code java.util.Map.Entry.class.getName()}</td>
  808.      * </tr>
  809.      * <tr>
  810.      * <td>{@code "Entry"}</td>
  811.      * <td>{@code java.util.Map.Entry.class.getCanonicalName()}</td>
  812.      * </tr>
  813.      * <tr>
  814.      * <td>{@code "ClassUtils"}</td>
  815.      * <td>{@code "org.apache.commons.lang3.ClassUtils"}</td>
  816.      * </tr>
  817.      * <tr>
  818.      * <td>{@code "ClassUtils[]"}</td>
  819.      * <td>{@code "[Lorg.apache.commons.lang3.ClassUtils;"}</td>
  820.      * </tr>
  821.      * <tr>
  822.      * <td>{@code "ClassUtils[][]"}</td>
  823.      * <td>{@code "[[Lorg.apache.commons.lang3.ClassUtils;"}</td>
  824.      * </tr>
  825.      * <tr>
  826.      * <td>{@code "ClassUtils[]"}</td>
  827.      * <td>{@code "org.apache.commons.lang3.ClassUtils[]"}</td>
  828.      * </tr>
  829.      * <tr>
  830.      * <td>{@code "ClassUtils[][]"}</td>
  831.      * <td>{@code "org.apache.commons.lang3.ClassUtils[][]"}</td>
  832.      * </tr>
  833.      * <tr>
  834.      * <td>{@code "int[]"}</td>
  835.      * <td>{@code "[I"}</td>
  836.      * </tr>
  837.      * <tr>
  838.      * <td>{@code "int[]"}</td>
  839.      * <td>{@code int[].class.getCanonicalName()}</td>
  840.      * </tr>
  841.      * <tr>
  842.      * <td>{@code "int[]"}</td>
  843.      * <td>{@code int[].class.getName()}</td>
  844.      * </tr>
  845.      * <tr>
  846.      * <td>{@code "int[][]"}</td>
  847.      * <td>{@code "[[I"}</td>
  848.      * </tr>
  849.      * <tr>
  850.      * <td>{@code "int[]"}</td>
  851.      * <td>{@code "int[]"}</td>
  852.      * </tr>
  853.      * <tr>
  854.      * <td>{@code "int[][]"}</td>
  855.      * <td>{@code "int[][]"}</td>
  856.      * </tr>
  857.      * </table>
  858.      *
  859.      * @param canonicalName the class name to get the short name for
  860.      * @return the canonical name of the class without the package name or an empty string
  861.      * @since 2.4
  862.      */
  863.     public static String getShortCanonicalName(final String canonicalName) {
  864.         return getShortClassName(getCanonicalName(canonicalName));
  865.     }

  866.     /**
  867.      * Gets the class name minus the package name from a {@link Class}.
  868.      *
  869.      * <p>
  870.      * This method simply gets the name using {@code Class.getName()} and then calls {@link #getShortClassName(String)}. See
  871.      * relevant notes there.
  872.      * </p>
  873.      *
  874.      * @param cls the class to get the short name for.
  875.      * @return the class name without the package name or an empty string. If the class is an inner class then the returned
  876.      *         value will contain the outer class or classes separated with {@code .} (dot) character.
  877.      */
  878.     public static String getShortClassName(final Class<?> cls) {
  879.         if (cls == null) {
  880.             return StringUtils.EMPTY;
  881.         }
  882.         return getShortClassName(cls.getName());
  883.     }

  884.     /**
  885.      * Gets the class name of the {@code object} without the package name or names.
  886.      *
  887.      * <p>
  888.      * The method looks up the class of the object and then converts the name of the class invoking
  889.      * {@link #getShortClassName(Class)} (see relevant notes there).
  890.      * </p>
  891.      *
  892.      * @param object the class to get the short name for, may be {@code null}
  893.      * @param valueIfNull the value to return if the object is {@code null}
  894.      * @return the class name of the object without the package name, or {@code valueIfNull} if the argument {@code object}
  895.      *         is {@code null}
  896.      */
  897.     public static String getShortClassName(final Object object, final String valueIfNull) {
  898.         if (object == null) {
  899.             return valueIfNull;
  900.         }
  901.         return getShortClassName(object.getClass());
  902.     }

  903.     /**
  904.      * Gets the class name minus the package name from a String.
  905.      *
  906.      * <p>
  907.      * The string passed in is assumed to be a class name - it is not checked. The string has to be formatted the way as the
  908.      * JDK method {@code Class.getName()} returns it, and not the usual way as we write it, for example in import
  909.      * statements, or as it is formatted by {@code Class.getCanonicalName()}.
  910.      * </p>
  911.      *
  912.      * <p>
  913.      * The difference is is significant only in case of classes that are inner classes of some other classes. In this case
  914.      * the separator between the outer and inner class (possibly on multiple hierarchy level) has to be {@code $} (dollar
  915.      * sign) and not {@code .} (dot), as it is returned by {@code Class.getName()}
  916.      * </p>
  917.      *
  918.      * <p>
  919.      * Note that this method is called from the {@link #getShortClassName(Class)} method using the string returned by
  920.      * {@code Class.getName()}.
  921.      * </p>
  922.      *
  923.      * <p>
  924.      * Note that this method differs from {@link #getSimpleName(Class)} in that this will return, for example
  925.      * {@code "Map.Entry"} whilst the {@link Class} variant will simply return {@code "Entry"}. In this example
  926.      * the argument {@code className} is the string {@code java.util.Map$Entry} (note the {@code $} sign.
  927.      * </p>
  928.      *
  929.      * @param className the className to get the short name for. It has to be formatted as returned by
  930.      *        {@code Class.getName()} and not {@code Class.getCanonicalName()}
  931.      * @return the class name of the class without the package name or an empty string. If the class is an inner class then
  932.      *         value contains the outer class or classes and the separator is replaced to be {@code .} (dot) character.
  933.      */
  934.     public static String getShortClassName(String className) {
  935.         if (StringUtils.isEmpty(className)) {
  936.             return StringUtils.EMPTY;
  937.         }

  938.         final StringBuilder arrayPrefix = new StringBuilder();

  939.         // Handle array encoding
  940.         if (className.startsWith("[")) {
  941.             while (className.charAt(0) == '[') {
  942.                 className = className.substring(1);
  943.                 arrayPrefix.append("[]");
  944.             }
  945.             // Strip Object type encoding
  946.             if (className.charAt(0) == 'L' && className.charAt(className.length() - 1) == ';') {
  947.                 className = className.substring(1, className.length() - 1);
  948.             }

  949.             if (reverseAbbreviationMap.containsKey(className)) {
  950.                 className = reverseAbbreviationMap.get(className);
  951.             }
  952.         }

  953.         final int lastDotIdx = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
  954.         final int innerIdx = className.indexOf(INNER_CLASS_SEPARATOR_CHAR, lastDotIdx == -1 ? 0 : lastDotIdx + 1);
  955.         String out = className.substring(lastDotIdx + 1);
  956.         if (innerIdx != -1) {
  957.             out = out.replace(INNER_CLASS_SEPARATOR_CHAR, PACKAGE_SEPARATOR_CHAR);
  958.         }
  959.         return out + arrayPrefix;
  960.     }

  961.     /**
  962.      * Null-safe version of {@code cls.getSimpleName()}
  963.      *
  964.      * @param cls the class for which to get the simple name; may be null
  965.      * @return the simple class name or the empty string in case the argument is {@code null}
  966.      * @since 3.0
  967.      * @see Class#getSimpleName()
  968.      */
  969.     public static String getSimpleName(final Class<?> cls) {
  970.         return getSimpleName(cls, StringUtils.EMPTY);
  971.     }

  972.     /**
  973.      * Null-safe version of {@code cls.getSimpleName()}
  974.      *
  975.      * @param cls the class for which to get the simple name; may be null
  976.      * @param valueIfNull the value to return if null
  977.      * @return the simple class name or {@code valueIfNull} if the argument {@code cls} is {@code null}
  978.      * @since 3.0
  979.      * @see Class#getSimpleName()
  980.      */
  981.     public static String getSimpleName(final Class<?> cls, final String valueIfNull) {
  982.         return cls == null ? valueIfNull : cls.getSimpleName();
  983.     }

  984.     /**
  985.      * Null-safe version of {@code object.getClass().getSimpleName()}
  986.      *
  987.      * <p>
  988.      * It is to note that this method is overloaded and in case the argument {@code object} is a {@link Class} object then
  989.      * the {@link #getSimpleName(Class)} will be invoked. If this is a significant possibility then the caller should check
  990.      * this case and call {@code
  991.      * getSimpleName(Class.class)} or just simply use the string literal {@code "Class"}, which is the result of the method
  992.      * in that case.
  993.      * </p>
  994.      *
  995.      * @param object the object for which to get the simple class name; may be null
  996.      * @return the simple class name or the empty string in case the argument is {@code null}
  997.      * @since 3.7
  998.      * @see Class#getSimpleName()
  999.      */
  1000.     public static String getSimpleName(final Object object) {
  1001.         return getSimpleName(object, StringUtils.EMPTY);
  1002.     }

  1003.     /**
  1004.      * Null-safe version of {@code object.getClass().getSimpleName()}
  1005.      *
  1006.      * @param object the object for which to get the simple class name; may be null
  1007.      * @param valueIfNull the value to return if {@code object} is {@code null}
  1008.      * @return the simple class name or {@code valueIfNull} if the argument {@code object} is {@code null}
  1009.      * @since 3.0
  1010.      * @see Class#getSimpleName()
  1011.      */
  1012.     public static String getSimpleName(final Object object, final String valueIfNull) {
  1013.         return object == null ? valueIfNull : object.getClass().getSimpleName();
  1014.     }

  1015.     /**
  1016.      * Gets an {@link Iterable} that can iterate over a class hierarchy in ascending (subclass to superclass) order,
  1017.      * excluding interfaces.
  1018.      *
  1019.      * @param type the type to get the class hierarchy from
  1020.      * @return Iterable an Iterable over the class hierarchy of the given class
  1021.      * @since 3.2
  1022.      */
  1023.     public static Iterable<Class<?>> hierarchy(final Class<?> type) {
  1024.         return hierarchy(type, Interfaces.EXCLUDE);
  1025.     }

  1026.     /**
  1027.      * Gets an {@link Iterable} that can iterate over a class hierarchy in ascending (subclass to superclass) order.
  1028.      *
  1029.      * @param type the type to get the class hierarchy from
  1030.      * @param interfacesBehavior switch indicating whether to include or exclude interfaces
  1031.      * @return Iterable an Iterable over the class hierarchy of the given class
  1032.      * @since 3.2
  1033.      */
  1034.     public static Iterable<Class<?>> hierarchy(final Class<?> type, final Interfaces interfacesBehavior) {
  1035.         final Iterable<Class<?>> classes = () -> {
  1036.             final MutableObject<Class<?>> next = new MutableObject<>(type);
  1037.             return new Iterator<Class<?>>() {

  1038.                 @Override
  1039.                 public boolean hasNext() {
  1040.                     return next.getValue() != null;
  1041.                 }

  1042.                 @Override
  1043.                 public Class<?> next() {
  1044.                     final Class<?> result = next.getValue();
  1045.                     next.setValue(result.getSuperclass());
  1046.                     return result;
  1047.                 }

  1048.                 @Override
  1049.                 public void remove() {
  1050.                     throw new UnsupportedOperationException();
  1051.                 }

  1052.             };
  1053.         };
  1054.         if (interfacesBehavior != Interfaces.INCLUDE) {
  1055.             return classes;
  1056.         }
  1057.         return () -> {
  1058.             final Set<Class<?>> seenInterfaces = new HashSet<>();
  1059.             final Iterator<Class<?>> wrapped = classes.iterator();

  1060.             return new Iterator<Class<?>>() {
  1061.                 Iterator<Class<?>> interfaces = Collections.emptyIterator();

  1062.                 @Override
  1063.                 public boolean hasNext() {
  1064.                     return interfaces.hasNext() || wrapped.hasNext();
  1065.                 }

  1066.                 @Override
  1067.                 public Class<?> next() {
  1068.                     if (interfaces.hasNext()) {
  1069.                         final Class<?> nextInterface = interfaces.next();
  1070.                         seenInterfaces.add(nextInterface);
  1071.                         return nextInterface;
  1072.                     }
  1073.                     final Class<?> nextSuperclass = wrapped.next();
  1074.                     final Set<Class<?>> currentInterfaces = new LinkedHashSet<>();
  1075.                     walkInterfaces(currentInterfaces, nextSuperclass);
  1076.                     interfaces = currentInterfaces.iterator();
  1077.                     return nextSuperclass;
  1078.                 }

  1079.                 @Override
  1080.                 public void remove() {
  1081.                     throw new UnsupportedOperationException();
  1082.                 }

  1083.                 private void walkInterfaces(final Set<Class<?>> addTo, final Class<?> c) {
  1084.                     for (final Class<?> iface : c.getInterfaces()) {
  1085.                         if (!seenInterfaces.contains(iface)) {
  1086.                             addTo.add(iface);
  1087.                         }
  1088.                         walkInterfaces(addTo, iface);
  1089.                     }
  1090.                 }

  1091.             };
  1092.         };
  1093.     }

  1094.     /**
  1095.      * Checks if one {@link Class} can be assigned to a variable of another {@link Class}.
  1096.      *
  1097.      * <p>
  1098.      * Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method, this method takes into account widenings of
  1099.      * primitive classes and {@code null}s.
  1100.      * </p>
  1101.      *
  1102.      * <p>
  1103.      * Primitive widenings allow an int to be assigned to a long, float or double. This method returns the correct result
  1104.      * for these cases.
  1105.      * </p>
  1106.      *
  1107.      * <p>
  1108.      * {@code null} may be assigned to any reference type. This method will return {@code true} if {@code null} is passed in
  1109.      * and the toClass is non-primitive.
  1110.      * </p>
  1111.      *
  1112.      * <p>
  1113.      * Specifically, this method tests whether the type represented by the specified {@link Class} parameter can be
  1114.      * converted to the type represented by this {@link Class} object via an identity conversion widening primitive or
  1115.      * widening reference conversion. See <em><a href="https://docs.oracle.com/javase/specs/">The Java Language
  1116.      * Specification</a></em>, sections 5.1.1, 5.1.2 and 5.1.4 for details.
  1117.      * </p>
  1118.      *
  1119.      * <p>
  1120.      * <strong>Since Lang 3.0,</strong> this method will default behavior for calculating assignability between primitive
  1121.      * and wrapper types <em>corresponding to the running Java version</em>; i.e. autoboxing will be the default behavior in
  1122.      * VMs running Java versions &gt; 1.5.
  1123.      * </p>
  1124.      *
  1125.      * @param cls the Class to check, may be null
  1126.      * @param toClass the Class to try to assign into, returns false if null
  1127.      * @return {@code true} if assignment possible
  1128.      */
  1129.     public static boolean isAssignable(final Class<?> cls, final Class<?> toClass) {
  1130.         return isAssignable(cls, toClass, true);
  1131.     }

  1132.     /**
  1133.      * Checks if one {@link Class} can be assigned to a variable of another {@link Class}.
  1134.      *
  1135.      * <p>
  1136.      * Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method, this method takes into account widenings of
  1137.      * primitive classes and {@code null}s.
  1138.      * </p>
  1139.      *
  1140.      * <p>
  1141.      * Primitive widenings allow an int to be assigned to a long, float or double. This method returns the correct result
  1142.      * for these cases.
  1143.      * </p>
  1144.      *
  1145.      * <p>
  1146.      * {@code null} may be assigned to any reference type. This method will return {@code true} if {@code null} is passed in
  1147.      * and the toClass is non-primitive.
  1148.      * </p>
  1149.      *
  1150.      * <p>
  1151.      * Specifically, this method tests whether the type represented by the specified {@link Class} parameter can be
  1152.      * converted to the type represented by this {@link Class} object via an identity conversion widening primitive or
  1153.      * widening reference conversion. See <em><a href="https://docs.oracle.com/javase/specs/">The Java Language
  1154.      * Specification</a></em>, sections 5.1.1, 5.1.2 and 5.1.4 for details.
  1155.      * </p>
  1156.      *
  1157.      * @param cls the Class to check, may be null
  1158.      * @param toClass the Class to try to assign into, returns false if null
  1159.      * @param autoboxing whether to use implicit autoboxing/unboxing between primitives and wrappers
  1160.      * @return {@code true} if assignment possible
  1161.      */
  1162.     public static boolean isAssignable(Class<?> cls, final Class<?> toClass, final boolean autoboxing) {
  1163.         if (toClass == null) {
  1164.             return false;
  1165.         }
  1166.         // have to check for null, as isAssignableFrom doesn't
  1167.         if (cls == null) {
  1168.             return !toClass.isPrimitive();
  1169.         }
  1170.         // autoboxing:
  1171.         if (autoboxing) {
  1172.             if (cls.isPrimitive() && !toClass.isPrimitive()) {
  1173.                 cls = primitiveToWrapper(cls);
  1174.                 if (cls == null) {
  1175.                     return false;
  1176.                 }
  1177.             }
  1178.             if (toClass.isPrimitive() && !cls.isPrimitive()) {
  1179.                 cls = wrapperToPrimitive(cls);
  1180.                 if (cls == null) {
  1181.                     return false;
  1182.                 }
  1183.             }
  1184.         }
  1185.         if (cls.equals(toClass)) {
  1186.             return true;
  1187.         }
  1188.         if (cls.isPrimitive()) {
  1189.             if (!toClass.isPrimitive()) {
  1190.                 return false;
  1191.             }
  1192.             if (Integer.TYPE.equals(cls)) {
  1193.                 return Long.TYPE.equals(toClass) || Float.TYPE.equals(toClass) || Double.TYPE.equals(toClass);
  1194.             }
  1195.             if (Long.TYPE.equals(cls)) {
  1196.                 return Float.TYPE.equals(toClass) || Double.TYPE.equals(toClass);
  1197.             }
  1198.             if (Boolean.TYPE.equals(cls)) {
  1199.                 return false;
  1200.             }
  1201.             if (Double.TYPE.equals(cls)) {
  1202.                 return false;
  1203.             }
  1204.             if (Float.TYPE.equals(cls)) {
  1205.                 return Double.TYPE.equals(toClass);
  1206.             }
  1207.             if (Character.TYPE.equals(cls)  || Short.TYPE.equals(cls)) {
  1208.                 return Integer.TYPE.equals(toClass) || Long.TYPE.equals(toClass) || Float.TYPE.equals(toClass) || Double.TYPE.equals(toClass);
  1209.             }
  1210.             if (Byte.TYPE.equals(cls)) {
  1211.                 return Short.TYPE.equals(toClass) || Integer.TYPE.equals(toClass) || Long.TYPE.equals(toClass) || Float.TYPE.equals(toClass)
  1212.                     || Double.TYPE.equals(toClass);
  1213.             }
  1214.             // should never get here
  1215.             return false;
  1216.         }
  1217.         return toClass.isAssignableFrom(cls);
  1218.     }

  1219.     /**
  1220.      * Checks if an array of Classes can be assigned to another array of Classes.
  1221.      *
  1222.      * <p>
  1223.      * This method calls {@link #isAssignable(Class, Class) isAssignable} for each Class pair in the input arrays. It can be
  1224.      * used to check if a set of arguments (the first parameter) are suitably compatible with a set of method parameter
  1225.      * types (the second parameter).
  1226.      * </p>
  1227.      *
  1228.      * <p>
  1229.      * Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method, this method takes into account widenings of
  1230.      * primitive classes and {@code null}s.
  1231.      * </p>
  1232.      *
  1233.      * <p>
  1234.      * Primitive widenings allow an int to be assigned to a {@code long}, {@code float} or {@code double}. This method
  1235.      * returns the correct result for these cases.
  1236.      * </p>
  1237.      *
  1238.      * <p>
  1239.      * {@code null} may be assigned to any reference type. This method will return {@code true} if {@code null} is passed in
  1240.      * and the toClass is non-primitive.
  1241.      * </p>
  1242.      *
  1243.      * <p>
  1244.      * Specifically, this method tests whether the type represented by the specified {@link Class} parameter can be
  1245.      * converted to the type represented by this {@link Class} object via an identity conversion widening primitive or
  1246.      * widening reference conversion. See <em><a href="https://docs.oracle.com/javase/specs/">The Java Language
  1247.      * Specification</a></em>, sections 5.1.1, 5.1.2 and 5.1.4 for details.
  1248.      * </p>
  1249.      *
  1250.      * <p>
  1251.      * <strong>Since Lang 3.0,</strong> this method will default behavior for calculating assignability between primitive
  1252.      * and wrapper types <em>corresponding to the running Java version</em>; i.e. autoboxing will be the default behavior in
  1253.      * VMs running Java versions &gt; 1.5.
  1254.      * </p>
  1255.      *
  1256.      * @param classArray the array of Classes to check, may be {@code null}
  1257.      * @param toClassArray the array of Classes to try to assign into, may be {@code null}
  1258.      * @return {@code true} if assignment possible
  1259.      */
  1260.     public static boolean isAssignable(final Class<?>[] classArray, final Class<?>... toClassArray) {
  1261.         return isAssignable(classArray, toClassArray, true);
  1262.     }

  1263.     /**
  1264.      * Checks if an array of Classes can be assigned to another array of Classes.
  1265.      *
  1266.      * <p>
  1267.      * This method calls {@link #isAssignable(Class, Class) isAssignable} for each Class pair in the input arrays. It can be
  1268.      * used to check if a set of arguments (the first parameter) are suitably compatible with a set of method parameter
  1269.      * types (the second parameter).
  1270.      * </p>
  1271.      *
  1272.      * <p>
  1273.      * Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method, this method takes into account widenings of
  1274.      * primitive classes and {@code null}s.
  1275.      * </p>
  1276.      *
  1277.      * <p>
  1278.      * Primitive widenings allow an int to be assigned to a {@code long}, {@code float} or {@code double}. This method
  1279.      * returns the correct result for these cases.
  1280.      * </p>
  1281.      *
  1282.      * <p>
  1283.      * {@code null} may be assigned to any reference type. This method will return {@code true} if {@code null} is passed in
  1284.      * and the toClass is non-primitive.
  1285.      * </p>
  1286.      *
  1287.      * <p>
  1288.      * Specifically, this method tests whether the type represented by the specified {@link Class} parameter can be
  1289.      * converted to the type represented by this {@link Class} object via an identity conversion widening primitive or
  1290.      * widening reference conversion. See <em><a href="https://docs.oracle.com/javase/specs/">The Java Language
  1291.      * Specification</a></em>, sections 5.1.1, 5.1.2 and 5.1.4 for details.
  1292.      * </p>
  1293.      *
  1294.      * @param classArray the array of Classes to check, may be {@code null}
  1295.      * @param toClassArray the array of Classes to try to assign into, may be {@code null}
  1296.      * @param autoboxing whether to use implicit autoboxing/unboxing between primitives and wrappers
  1297.      * @return {@code true} if assignment possible
  1298.      */
  1299.     public static boolean isAssignable(Class<?>[] classArray, Class<?>[] toClassArray, final boolean autoboxing) {
  1300.         if (!ArrayUtils.isSameLength(classArray, toClassArray)) {
  1301.             return false;
  1302.         }
  1303.         classArray = ArrayUtils.nullToEmpty(classArray);
  1304.         toClassArray = ArrayUtils.nullToEmpty(toClassArray);
  1305.         for (int i = 0; i < classArray.length; i++) {
  1306.             if (!isAssignable(classArray[i], toClassArray[i], autoboxing)) {
  1307.                 return false;
  1308.             }
  1309.         }
  1310.         return true;
  1311.     }

  1312.     /**
  1313.      * Is the specified class an inner class or static nested class.
  1314.      *
  1315.      * @param cls the class to check, may be null
  1316.      * @return {@code true} if the class is an inner or static nested class, false if not or {@code null}
  1317.      */
  1318.     public static boolean isInnerClass(final Class<?> cls) {
  1319.         return cls != null && cls.getEnclosingClass() != null;
  1320.     }

  1321.     /**
  1322.      * Returns whether the given {@code type} is a primitive or primitive wrapper ({@link Boolean}, {@link Byte},
  1323.      * {@link Character}, {@link Short}, {@link Integer}, {@link Long}, {@link Double}, {@link Float}).
  1324.      *
  1325.      * @param type The class to query or null.
  1326.      * @return true if the given {@code type} is a primitive or primitive wrapper ({@link Boolean}, {@link Byte},
  1327.      *         {@link Character}, {@link Short}, {@link Integer}, {@link Long}, {@link Double}, {@link Float}).
  1328.      * @since 3.1
  1329.      */
  1330.     public static boolean isPrimitiveOrWrapper(final Class<?> type) {
  1331.         if (type == null) {
  1332.             return false;
  1333.         }
  1334.         return type.isPrimitive() || isPrimitiveWrapper(type);
  1335.     }
  1336.     /**
  1337.      * Returns whether the given {@code type} is a primitive wrapper ({@link Boolean}, {@link Byte}, {@link Character},
  1338.      * {@link Short}, {@link Integer}, {@link Long}, {@link Double}, {@link Float}).
  1339.      *
  1340.      * @param type The class to query or null.
  1341.      * @return true if the given {@code type} is a primitive wrapper ({@link Boolean}, {@link Byte}, {@link Character},
  1342.      *         {@link Short}, {@link Integer}, {@link Long}, {@link Double}, {@link Float}).
  1343.      * @since 3.1
  1344.      */
  1345.     public static boolean isPrimitiveWrapper(final Class<?> type) {
  1346.         return wrapperPrimitiveMap.containsKey(type);
  1347.     }

  1348.     /**
  1349.      * Tests whether a {@link Class} is public.
  1350.      * @param cls Class to test.
  1351.      * @return {@code true} if {@code cls} is public.
  1352.      * @since 3.13.0
  1353.      */
  1354.     public static boolean isPublic(final Class<?> cls) {
  1355.         return Modifier.isPublic(cls.getModifiers());
  1356.     }

  1357.     /**
  1358.      * Converts the specified array of primitive Class objects to an array of its corresponding wrapper Class objects.
  1359.      *
  1360.      * @param classes the class array to convert, may be null or empty
  1361.      * @return an array which contains for each given class, the wrapper class or the original class if class is not a
  1362.      *         primitive. {@code null} if null input. Empty array if an empty array passed in.
  1363.      * @since 2.1
  1364.      */
  1365.     public static Class<?>[] primitivesToWrappers(final Class<?>... classes) {
  1366.         if (classes == null) {
  1367.             return null;
  1368.         }

  1369.         if (classes.length == 0) {
  1370.             return classes;
  1371.         }

  1372.         final Class<?>[] convertedClasses = new Class[classes.length];
  1373.         Arrays.setAll(convertedClasses, i -> primitiveToWrapper(classes[i]));
  1374.         return convertedClasses;
  1375.     }

  1376.     /**
  1377.      * Converts the specified primitive Class object to its corresponding wrapper Class object.
  1378.      *
  1379.      * <p>
  1380.      * NOTE: From v2.2, this method handles {@code Void.TYPE}, returning {@code Void.TYPE}.
  1381.      * </p>
  1382.      *
  1383.      * @param cls the class to convert, may be null
  1384.      * @return the wrapper class for {@code cls} or {@code cls} if {@code cls} is not a primitive. {@code null} if null
  1385.      *         input.
  1386.      * @since 2.1
  1387.      */
  1388.     public static Class<?> primitiveToWrapper(final Class<?> cls) {
  1389.         Class<?> convertedClass = cls;
  1390.         if (cls != null && cls.isPrimitive()) {
  1391.             convertedClass = primitiveWrapperMap.get(cls);
  1392.         }
  1393.         return convertedClass;
  1394.     }

  1395.     /**
  1396.      * Converts a class name to a JLS style class name.
  1397.      *
  1398.      * @param className the class name
  1399.      * @return the converted name
  1400.      * @throws NullPointerException if the className is null
  1401.      */
  1402.     private static String toCanonicalName(final String className) {
  1403.         String canonicalName = StringUtils.deleteWhitespace(className);
  1404.         Objects.requireNonNull(canonicalName, "className");
  1405.         if (canonicalName.endsWith("[]")) {
  1406.             final StringBuilder classNameBuffer = new StringBuilder();
  1407.             while (canonicalName.endsWith("[]")) {
  1408.                 canonicalName = canonicalName.substring(0, canonicalName.length() - 2);
  1409.                 classNameBuffer.append("[");
  1410.             }
  1411.             final String abbreviation = abbreviationMap.get(canonicalName);
  1412.             if (abbreviation != null) {
  1413.                 classNameBuffer.append(abbreviation);
  1414.             } else {
  1415.                 classNameBuffer.append("L").append(canonicalName).append(";");
  1416.             }
  1417.             canonicalName = classNameBuffer.toString();
  1418.         }
  1419.         return canonicalName;
  1420.     }

  1421.     /**
  1422.      * Converts an array of {@link Object} in to an array of {@link Class} objects. If any of these objects is null, a null
  1423.      * element will be inserted into the array.
  1424.      *
  1425.      * <p>
  1426.      * This method returns {@code null} for a {@code null} input array.
  1427.      * </p>
  1428.      *
  1429.      * @param array an {@link Object} array
  1430.      * @return a {@link Class} array, {@code null} if null array input
  1431.      * @since 2.4
  1432.      */
  1433.     public static Class<?>[] toClass(final Object... array) {
  1434.         if (array == null) {
  1435.             return null;
  1436.         }
  1437.         if (array.length == 0) {
  1438.             return ArrayUtils.EMPTY_CLASS_ARRAY;
  1439.         }
  1440.         final Class<?>[] classes = new Class[array.length];
  1441.         Arrays.setAll(classes, i -> array[i] == null ? null : array[i].getClass());
  1442.         return classes;
  1443.     }

  1444.     /**
  1445.      * Decides if the part that was just copied to its destination location in the work array can be kept as it was copied
  1446.      * or must be abbreviated. It must be kept when the part is the last one, which is the simple name of the class. In this
  1447.      * case the {@code source} index, from where the characters are copied points one position after the last character,
  1448.      * a.k.a. {@code source ==
  1449.      * originalLength}
  1450.      *
  1451.      * <p>
  1452.      * If the part is not the last one then it can be kept unabridged if the number of the characters copied so far plus the
  1453.      * character that are to be copied is less than or equal to the desired length.
  1454.      * </p>
  1455.      *
  1456.      * @param runAheadTarget the target index (where the characters were copied to) pointing after the last character copied
  1457.      *        when the current part was copied
  1458.      * @param source the source index (where the characters were copied from) pointing after the last character copied when
  1459.      *        the current part was copied
  1460.      * @param originalLength the original length of the class full name, which is abbreviated
  1461.      * @param desiredLength the desired length of the abbreviated class name
  1462.      * @return {@code true} if it can be kept in its original length {@code false} if the current part has to be abbreviated
  1463.      *         and
  1464.      */
  1465.     private static boolean useFull(final int runAheadTarget, final int source, final int originalLength, final int desiredLength) {
  1466.         return source >= originalLength || runAheadTarget + originalLength - source <= desiredLength;
  1467.     }

  1468.     /**
  1469.      * Converts the specified array of wrapper Class objects to an array of its corresponding primitive Class objects.
  1470.      *
  1471.      * <p>
  1472.      * This method invokes {@code wrapperToPrimitive()} for each element of the passed in array.
  1473.      * </p>
  1474.      *
  1475.      * @param classes the class array to convert, may be null or empty
  1476.      * @return an array which contains for each given class, the primitive class or <b>null</b> if the original class is not
  1477.      *         a wrapper class. {@code null} if null input. Empty array if an empty array passed in.
  1478.      * @see #wrapperToPrimitive(Class)
  1479.      * @since 2.4
  1480.      */
  1481.     public static Class<?>[] wrappersToPrimitives(final Class<?>... classes) {
  1482.         if (classes == null) {
  1483.             return null;
  1484.         }

  1485.         if (classes.length == 0) {
  1486.             return classes;
  1487.         }

  1488.         final Class<?>[] convertedClasses = new Class[classes.length];
  1489.         Arrays.setAll(convertedClasses, i -> wrapperToPrimitive(classes[i]));
  1490.         return convertedClasses;
  1491.     }

  1492.     /**
  1493.      * Converts the specified wrapper class to its corresponding primitive class.
  1494.      *
  1495.      * <p>
  1496.      * This method is the counter part of {@code primitiveToWrapper()}. If the passed in class is a wrapper class for a
  1497.      * primitive type, this primitive type will be returned (e.g. {@code Integer.TYPE} for {@code Integer.class}). For other
  1498.      * classes, or if the parameter is <b>null</b>, the return value is <b>null</b>.
  1499.      * </p>
  1500.      *
  1501.      * @param cls the class to convert, may be <b>null</b>
  1502.      * @return the corresponding primitive type if {@code cls} is a wrapper class, <b>null</b> otherwise
  1503.      * @see #primitiveToWrapper(Class)
  1504.      * @since 2.4
  1505.      */
  1506.     public static Class<?> wrapperToPrimitive(final Class<?> cls) {
  1507.         return wrapperPrimitiveMap.get(cls);
  1508.     }

  1509.     /**
  1510.      * ClassUtils instances should NOT be constructed in standard programming. Instead, the class should be used as
  1511.      * {@code ClassUtils.getShortClassName(cls)}.
  1512.      *
  1513.      * <p>
  1514.      * This constructor is public to permit tools that require a JavaBean instance to operate.
  1515.      * </p>
  1516.      *
  1517.      * @deprecated TODO Make private in 4.0.
  1518.      */
  1519.     @Deprecated
  1520.     public ClassUtils() {
  1521.         // empty
  1522.     }

  1523. }