Coverage Report - org.apache.commons.lang3.ClassUtils
 
Classes in this File Line Coverage Branch Coverage Complexity
ClassUtils
95%
268/280
93%
212/226
4.975
 
 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  
 
 19  
 import java.lang.reflect.Method;
 20  
 import java.lang.reflect.Modifier;
 21  
 import java.util.ArrayList;
 22  
 import java.util.HashMap;
 23  
 import java.util.HashSet;
 24  
 import java.util.LinkedHashSet;
 25  
 import java.util.List;
 26  
 import java.util.Map;
 27  
 
 28  
 
 29  
 /**
 30  
  * <p>Operates on classes without using reflection.</p>
 31  
  *
 32  
  * <p>This class handles invalid {@code null} inputs as best it can.
 33  
  * Each method documents its behaviour in more detail.</p>
 34  
  *
 35  
  * <p>The notion of a {@code canonical name} includes the human
 36  
  * readable name for the type, for example {@code int[]}. The
 37  
  * non-canonical method variants work with the JVM names, such as
 38  
  * {@code [I}. </p>
 39  
  *
 40  
  * @since 2.0
 41  
  * @version $Id: ClassUtils.java 1436770 2013-01-22 07:09:45Z ggregory $
 42  
  */
 43  
 public class ClassUtils {
 44  
 
 45  
     /**
 46  
      * <p>The package separator character: <code>'&#x2e;' == {@value}</code>.</p>
 47  
      */
 48  
     public static final char PACKAGE_SEPARATOR_CHAR = '.';
 49  
 
 50  
     /**
 51  
      * <p>The package separator String: <code>"&#x2e;"</code>.</p>
 52  
      */
 53  1
     public static final String PACKAGE_SEPARATOR = String.valueOf(PACKAGE_SEPARATOR_CHAR);
 54  
 
 55  
     /**
 56  
      * <p>The inner class separator character: <code>'$' == {@value}</code>.</p>
 57  
      */
 58  
     public static final char INNER_CLASS_SEPARATOR_CHAR = '$';
 59  
 
 60  
     /**
 61  
      * <p>The inner class separator String: {@code "$"}.</p>
 62  
      */
 63  1
     public static final String INNER_CLASS_SEPARATOR = String.valueOf(INNER_CLASS_SEPARATOR_CHAR);
 64  
 
 65  
     /**
 66  
      * Maps primitive {@code Class}es to their corresponding wrapper {@code Class}.
 67  
      */
 68  1
     private static final Map<Class<?>, Class<?>> primitiveWrapperMap = new HashMap<Class<?>, Class<?>>();
 69  
     static {
 70  1
          primitiveWrapperMap.put(Boolean.TYPE, Boolean.class);
 71  1
          primitiveWrapperMap.put(Byte.TYPE, Byte.class);
 72  1
          primitiveWrapperMap.put(Character.TYPE, Character.class);
 73  1
          primitiveWrapperMap.put(Short.TYPE, Short.class);
 74  1
          primitiveWrapperMap.put(Integer.TYPE, Integer.class);
 75  1
          primitiveWrapperMap.put(Long.TYPE, Long.class);
 76  1
          primitiveWrapperMap.put(Double.TYPE, Double.class);
 77  1
          primitiveWrapperMap.put(Float.TYPE, Float.class);
 78  1
          primitiveWrapperMap.put(Void.TYPE, Void.TYPE);
 79  
     }
 80  
 
 81  
     /**
 82  
      * Maps wrapper {@code Class}es to their corresponding primitive types.
 83  
      */
 84  1
     private static final Map<Class<?>, Class<?>> wrapperPrimitiveMap = new HashMap<Class<?>, Class<?>>();
 85  
     static {
 86  1
         for (final Class<?> primitiveClass : primitiveWrapperMap.keySet()) {
 87  9
             final Class<?> wrapperClass = primitiveWrapperMap.get(primitiveClass);
 88  9
             if (!primitiveClass.equals(wrapperClass)) {
 89  8
                 wrapperPrimitiveMap.put(wrapperClass, primitiveClass);
 90  
             }
 91  9
         }
 92  
     }
 93  
 
 94  
     /**
 95  
      * Maps a primitive class name to its corresponding abbreviation used in array class names.
 96  
      */
 97  1
     private static final Map<String, String> abbreviationMap = new HashMap<String, String>();
 98  
 
 99  
     /**
 100  
      * Maps an abbreviation used in array class names to corresponding primitive class name.
 101  
      */
 102  1
     private static final Map<String, String> reverseAbbreviationMap = new HashMap<String, String>();
 103  
 
 104  
     /**
 105  
      * Add primitive type abbreviation to maps of abbreviations.
 106  
      *
 107  
      * @param primitive Canonical name of primitive type
 108  
      * @param abbreviation Corresponding abbreviation of primitive type
 109  
      */
 110  
     private static void addAbbreviation(final String primitive, final String abbreviation) {
 111  8
         abbreviationMap.put(primitive, abbreviation);
 112  8
         reverseAbbreviationMap.put(abbreviation, primitive);
 113  8
     }
 114  
 
 115  
     /**
 116  
      * Feed abbreviation maps
 117  
      */
 118  
     static {
 119  1
         addAbbreviation("int", "I");
 120  1
         addAbbreviation("boolean", "Z");
 121  1
         addAbbreviation("float", "F");
 122  1
         addAbbreviation("long", "J");
 123  1
         addAbbreviation("short", "S");
 124  1
         addAbbreviation("byte", "B");
 125  1
         addAbbreviation("double", "D");
 126  1
         addAbbreviation("char", "C");
 127  1
     }
 128  
 
 129  
     /**
 130  
      * <p>ClassUtils instances should NOT be constructed in standard programming.
 131  
      * Instead, the class should be used as
 132  
      * {@code ClassUtils.getShortClassName(cls)}.</p>
 133  
      *
 134  
      * <p>This constructor is public to permit tools that require a JavaBean
 135  
      * instance to operate.</p>
 136  
      */
 137  
     public ClassUtils() {
 138  6
       super();
 139  6
     }
 140  
 
 141  
     // Short class name
 142  
     // ----------------------------------------------------------------------
 143  
     /**
 144  
      * <p>Gets the class name minus the package name for an {@code Object}.</p>
 145  
      *
 146  
      * @param object  the class to get the short name for, may be null
 147  
      * @param valueIfNull  the value to return if null
 148  
      * @return the class name of the object without the package name, or the null value
 149  
      */
 150  
     public static String getShortClassName(final Object object, final String valueIfNull) {
 151  11
         if (object == null) {
 152  1
             return valueIfNull;
 153  
         }
 154  10
         return getShortClassName(object.getClass());
 155  
     }
 156  
 
 157  
     /**
 158  
      * <p>Gets the class name minus the package name from a {@code Class}.</p>
 159  
      * 
 160  
      * <p>Consider using the Java 5 API {@link Class#getSimpleName()} instead. 
 161  
      * The one known difference is that this code will return {@code "Map.Entry"} while 
 162  
      * the {@code java.lang.Class} variant will simply return {@code "Entry"}. </p>
 163  
      *
 164  
      * @param cls  the class to get the short name for.
 165  
      * @return the class name without the package name or an empty string
 166  
      */
 167  
     public static String getShortClassName(final Class<?> cls) {
 168  113
         if (cls == null) {
 169  1
             return StringUtils.EMPTY;
 170  
         }
 171  112
         return getShortClassName(cls.getName());
 172  
     }
 173  
 
 174  
     /**
 175  
      * <p>Gets the class name minus the package name from a String.</p>
 176  
      *
 177  
      * <p>The string passed in is assumed to be a class name - it is not checked.</p>
 178  
 
 179  
      * <p>Note that this method differs from Class.getSimpleName() in that this will 
 180  
      * return {@code "Map.Entry"} whilst the {@code java.lang.Class} variant will simply 
 181  
      * return {@code "Entry"}. </p>
 182  
      *
 183  
      * @param className  the className to get the short name for
 184  
      * @return the class name of the class without the package name or an empty string
 185  
      */
 186  
     public static String getShortClassName(String className) {   
 187  144
         if (StringUtils.isEmpty(className)) {
 188  2
             return StringUtils.EMPTY;
 189  
         }
 190  
 
 191  142
         final StringBuilder arrayPrefix = new StringBuilder();
 192  
 
 193  
         // Handle array encoding
 194  142
         if (className.startsWith("[")) {
 195  32
             while (className.charAt(0) == '[') {
 196  19
                 className = className.substring(1);
 197  19
                 arrayPrefix.append("[]");
 198  
             }
 199  
             // Strip Object type encoding
 200  13
             if (className.charAt(0) == 'L' && className.charAt(className.length() - 1) == ';') {
 201  5
                 className = className.substring(1, className.length() - 1);
 202  
             }
 203  
         }
 204  
 
 205  142
         if (reverseAbbreviationMap.containsKey(className)) {
 206  8
             className = reverseAbbreviationMap.get(className);
 207  
         }
 208  
 
 209  142
         final int lastDotIdx = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
 210  142
         final int innerIdx = className.indexOf(
 211  
                 INNER_CLASS_SEPARATOR_CHAR, lastDotIdx == -1 ? 0 : lastDotIdx + 1);
 212  142
         String out = className.substring(lastDotIdx + 1);
 213  142
         if (innerIdx != -1) {
 214  22
             out = out.replace(INNER_CLASS_SEPARATOR_CHAR, PACKAGE_SEPARATOR_CHAR);
 215  
         }
 216  142
         return out + arrayPrefix;
 217  
     }
 218  
 
 219  
     /**
 220  
      * <p>Null-safe version of <code>aClass.getSimpleName()</code></p>
 221  
      *
 222  
      * @param cls the class for which to get the simple name.
 223  
      * @return the simple class name.
 224  
      * @since 3.0
 225  
      * @see Class#getSimpleName()
 226  
      */
 227  
     public static String getSimpleName(final Class<?> cls) {
 228  29
         if (cls == null) {
 229  1
             return StringUtils.EMPTY;
 230  
         }
 231  28
         return cls.getSimpleName();
 232  
     }
 233  
 
 234  
     /**
 235  
      * <p>Null-safe version of <code>aClass.getSimpleName()</code></p>
 236  
      *
 237  
      * @param object the object for which to get the simple class name.
 238  
      * @param valueIfNull the value to return if <code>object</code> is <code>null</code>
 239  
      * @return the simple class name.
 240  
      * @since 3.0
 241  
      * @see Class#getSimpleName()
 242  
      */
 243  
     public static String getSimpleName(final Object object, final String valueIfNull) {
 244  4
         if (object == null) {
 245  1
             return valueIfNull;
 246  
         }
 247  3
         return getSimpleName(object.getClass());
 248  
     }
 249  
 
 250  
     // Package name
 251  
     // ----------------------------------------------------------------------
 252  
     /**
 253  
      * <p>Gets the package name of an {@code Object}.</p>
 254  
      *
 255  
      * @param object  the class to get the package name for, may be null
 256  
      * @param valueIfNull  the value to return if null
 257  
      * @return the package name of the object, or the null value
 258  
      */
 259  
     public static String getPackageName(final Object object, final String valueIfNull) {
 260  3
         if (object == null) {
 261  1
             return valueIfNull;
 262  
         }
 263  2
         return getPackageName(object.getClass());
 264  
     }
 265  
 
 266  
     /**
 267  
      * <p>Gets the package name of a {@code Class}.</p>
 268  
      *
 269  
      * @param cls  the class to get the package name for, may be {@code null}.
 270  
      * @return the package name or an empty string
 271  
      */
 272  
     public static String getPackageName(final Class<?> cls) {
 273  19
         if (cls == null) {
 274  1
             return StringUtils.EMPTY;
 275  
         }
 276  18
         return getPackageName(cls.getName());
 277  
     }
 278  
 
 279  
     /**
 280  
      * <p>Gets the package name from a {@code String}.</p>
 281  
      *
 282  
      * <p>The string passed in is assumed to be a class name - it is not checked.</p>
 283  
      * <p>If the class is unpackaged, return an empty string.</p>
 284  
      *
 285  
      * @param className  the className to get the package name for, may be {@code null}
 286  
      * @return the package name or an empty string
 287  
      */
 288  
     public static String getPackageName(String className) {
 289  50
         if (StringUtils.isEmpty(className)) {
 290  2
             return StringUtils.EMPTY;
 291  
         }
 292  
 
 293  
         // Strip array encoding
 294  66
         while (className.charAt(0) == '[') {
 295  18
             className = className.substring(1);
 296  
         }
 297  
         // Strip Object type encoding
 298  48
         if (className.charAt(0) == 'L' && className.charAt(className.length() - 1) == ';') {
 299  4
             className = className.substring(1);
 300  
         }
 301  
 
 302  48
         final int i = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
 303  48
         if (i == -1) {
 304  16
             return StringUtils.EMPTY;
 305  
         }
 306  32
         return className.substring(0, i);
 307  
     }
 308  
 
 309  
     // Superclasses/Superinterfaces
 310  
     // ----------------------------------------------------------------------
 311  
     /**
 312  
      * <p>Gets a {@code List} of superclasses for the given class.</p>
 313  
      *
 314  
      * @param cls  the class to look up, may be {@code null}
 315  
      * @return the {@code List} of superclasses in order going up from this one
 316  
      *  {@code null} if null input
 317  
      */
 318  
     public static List<Class<?>> getAllSuperclasses(final Class<?> cls) {
 319  3
         if (cls == null) {
 320  1
             return null;
 321  
         }
 322  2
         final List<Class<?>> classes = new ArrayList<Class<?>>();
 323  2
         Class<?> superclass = cls.getSuperclass();
 324  6
         while (superclass != null) {
 325  4
             classes.add(superclass);
 326  4
             superclass = superclass.getSuperclass();
 327  
         }
 328  2
         return classes;
 329  
     }
 330  
 
 331  
     /**
 332  
      * <p>Gets a {@code List} of all interfaces implemented by the given
 333  
      * class and its superclasses.</p>
 334  
      *
 335  
      * <p>The order is determined by looking through each interface in turn as
 336  
      * declared in the source file and following its hierarchy up. Then each
 337  
      * superclass is considered in the same way. Later duplicates are ignored,
 338  
      * so the order is maintained.</p>
 339  
      *
 340  
      * @param cls  the class to look up, may be {@code null}
 341  
      * @return the {@code List} of interfaces in order,
 342  
      *  {@code null} if null input
 343  
      */
 344  
     public static List<Class<?>> getAllInterfaces(final Class<?> cls) {
 345  42
         if (cls == null) {
 346  1
             return null;
 347  
         }
 348  
 
 349  41
         final LinkedHashSet<Class<?>> interfacesFound = new LinkedHashSet<Class<?>>();
 350  41
         getAllInterfaces(cls, interfacesFound);
 351  
 
 352  41
         return new ArrayList<Class<?>>(interfacesFound);
 353  
     }
 354  
 
 355  
     /**
 356  
      * Get the interfaces for the specified class.
 357  
      *
 358  
      * @param cls  the class to look up, may be {@code null}
 359  
      * @param interfacesFound the {@code Set} of interfaces for the class
 360  
      */
 361  
     private static void getAllInterfaces(Class<?> cls, final HashSet<Class<?>> interfacesFound) {
 362  247
         while (cls != null) {
 363  162
             final Class<?>[] interfaces = cls.getInterfaces();
 364  
 
 365  210
             for (final Class<?> i : interfaces) {
 366  48
                 if (interfacesFound.add(i)) {
 367  44
                     getAllInterfaces(i, interfacesFound);
 368  
                 }
 369  
             }
 370  
 
 371  162
             cls = cls.getSuperclass();
 372  162
          }
 373  85
      }
 374  
 
 375  
     // Convert list
 376  
     // ----------------------------------------------------------------------
 377  
     /**
 378  
      * <p>Given a {@code List} of class names, this method converts them into classes.</p>
 379  
      *
 380  
      * <p>A new {@code List} is returned. If the class name cannot be found, {@code null}
 381  
      * is stored in the {@code List}. If the class name in the {@code List} is
 382  
      * {@code null}, {@code null} is stored in the output {@code List}.</p>
 383  
      *
 384  
      * @param classNames  the classNames to change
 385  
      * @return a {@code List} of Class objects corresponding to the class names,
 386  
      *  {@code null} if null input
 387  
      * @throws ClassCastException if classNames contains a non String entry
 388  
      */
 389  
     public static List<Class<?>> convertClassNamesToClasses(final List<String> classNames) {
 390  4
         if (classNames == null) {
 391  1
             return null;
 392  
         }
 393  3
         final List<Class<?>> classes = new ArrayList<Class<?>>(classNames.size());
 394  3
         for (final String className : classNames) {
 395  
             try {
 396  6
                 classes.add(Class.forName(className));
 397  2
             } catch (final Exception ex) {
 398  2
                 classes.add(null);
 399  4
             }
 400  6
         }
 401  2
         return classes;
 402  
     }
 403  
 
 404  
     /**
 405  
      * <p>Given a {@code List} of {@code Class} objects, this method converts
 406  
      * them into class names.</p>
 407  
      *
 408  
      * <p>A new {@code List} is returned. {@code null} objects will be copied into
 409  
      * the returned list as {@code null}.</p>
 410  
      *
 411  
      * @param classes  the classes to change
 412  
      * @return a {@code List} of class names corresponding to the Class objects,
 413  
      *  {@code null} if null input
 414  
      * @throws ClassCastException if {@code classes} contains a non-{@code Class} entry
 415  
      */
 416  
     public static List<String> convertClassesToClassNames(final List<Class<?>> classes) {
 417  4
         if (classes == null) {
 418  1
             return null;
 419  
         }
 420  3
         final List<String> classNames = new ArrayList<String>(classes.size());
 421  3
         for (final Class<?> cls : classes) {
 422  6
             if (cls == null) {
 423  2
                 classNames.add(null);
 424  
             } else {
 425  4
                 classNames.add(cls.getName());
 426  
             }
 427  6
         }
 428  2
         return classNames;
 429  
     }
 430  
 
 431  
     // Is assignable
 432  
     // ----------------------------------------------------------------------
 433  
     /**
 434  
      * <p>Checks if an array of Classes can be assigned to another array of Classes.</p>
 435  
      *
 436  
      * <p>This method calls {@link #isAssignable(Class, Class) isAssignable} for each
 437  
      * Class pair in the input arrays. It can be used to check if a set of arguments
 438  
      * (the first parameter) are suitably compatible with a set of method parameter types
 439  
      * (the second parameter).</p>
 440  
      *
 441  
      * <p>Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method, this
 442  
      * method takes into account widenings of primitive classes and
 443  
      * {@code null}s.</p>
 444  
      *
 445  
      * <p>Primitive widenings allow an int to be assigned to a {@code long},
 446  
      * {@code float} or {@code double}. This method returns the correct
 447  
      * result for these cases.</p>
 448  
      *
 449  
      * <p>{@code Null} may be assigned to any reference type. This method will
 450  
      * return {@code true} if {@code null} is passed in and the toClass is
 451  
      * non-primitive.</p>
 452  
      *
 453  
      * <p>Specifically, this method tests whether the type represented by the
 454  
      * specified {@code Class} parameter can be converted to the type
 455  
      * represented by this {@code Class} object via an identity conversion
 456  
      * widening primitive or widening reference conversion. See
 457  
      * <em><a href="http://java.sun.com/docs/books/jls/">The Java Language Specification</a></em>,
 458  
      * sections 5.1.1, 5.1.2 and 5.1.4 for details.</p>
 459  
      *
 460  
      * <p><strong>Since Lang 3.0,</strong> this method will default behavior for
 461  
      * calculating assignability between primitive and wrapper types <em>corresponding
 462  
      * to the running Java version</em>; i.e. autoboxing will be the default
 463  
      * behavior in VMs running Java versions >= 1.5.</p>
 464  
      *
 465  
      * @param classArray  the array of Classes to check, may be {@code null}
 466  
      * @param toClassArray  the array of Classes to try to assign into, may be {@code null}
 467  
      * @return {@code true} if assignment possible
 468  
      */
 469  
     public static boolean isAssignable(final Class<?>[] classArray, final Class<?>... toClassArray) {
 470  15
         return isAssignable(classArray, toClassArray, SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_5));
 471  
     }
 472  
 
 473  
     /**
 474  
      * <p>Checks if an array of Classes can be assigned to another array of Classes.</p>
 475  
      *
 476  
      * <p>This method calls {@link #isAssignable(Class, Class) isAssignable} for each
 477  
      * Class pair in the input arrays. It can be used to check if a set of arguments
 478  
      * (the first parameter) are suitably compatible with a set of method parameter types
 479  
      * (the second parameter).</p>
 480  
      *
 481  
      * <p>Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method, this
 482  
      * method takes into account widenings of primitive classes and
 483  
      * {@code null}s.</p>
 484  
      *
 485  
      * <p>Primitive widenings allow an int to be assigned to a {@code long},
 486  
      * {@code float} or {@code double}. This method returns the correct
 487  
      * result for these cases.</p>
 488  
      *
 489  
      * <p>{@code Null} may be assigned to any reference type. This method will
 490  
      * return {@code true} if {@code null} is passed in and the toClass is
 491  
      * non-primitive.</p>
 492  
      *
 493  
      * <p>Specifically, this method tests whether the type represented by the
 494  
      * specified {@code Class} parameter can be converted to the type
 495  
      * represented by this {@code Class} object via an identity conversion
 496  
      * widening primitive or widening reference conversion. See
 497  
      * <em><a href="http://java.sun.com/docs/books/jls/">The Java Language Specification</a></em>,
 498  
      * sections 5.1.1, 5.1.2 and 5.1.4 for details.</p>
 499  
      *
 500  
      * @param classArray  the array of Classes to check, may be {@code null}
 501  
      * @param toClassArray  the array of Classes to try to assign into, may be {@code null}
 502  
      * @param autoboxing  whether to use implicit autoboxing/unboxing between primitives and wrappers
 503  
      * @return {@code true} if assignment possible
 504  
      */
 505  
     public static boolean isAssignable(Class<?>[] classArray, Class<?>[] toClassArray, final boolean autoboxing) {
 506  278
         if (ArrayUtils.isSameLength(classArray, toClassArray) == false) {
 507  49
             return false;
 508  
         }
 509  229
         if (classArray == null) {
 510  6
             classArray = ArrayUtils.EMPTY_CLASS_ARRAY;
 511  
         }
 512  229
         if (toClassArray == null) {
 513  6
             toClassArray = ArrayUtils.EMPTY_CLASS_ARRAY;
 514  
         }
 515  350
         for (int i = 0; i < classArray.length; i++) {
 516  226
             if (isAssignable(classArray[i], toClassArray[i], autoboxing) == false) {
 517  105
                 return false;
 518  
             }
 519  
         }
 520  124
         return true;
 521  
     }
 522  
 
 523  
     /**
 524  
      * Returns whether the given {@code type} is a primitive or primitive wrapper ({@link Boolean}, {@link Byte}, {@link Character},
 525  
      * {@link Short}, {@link Integer}, {@link Long}, {@link Double}, {@link Float}).
 526  
      * 
 527  
      * @param type
 528  
      *            The class to query or null.
 529  
      * @return true if the given {@code type} is a primitive or primitive wrapper ({@link Boolean}, {@link Byte}, {@link Character},
 530  
      *         {@link Short}, {@link Integer}, {@link Long}, {@link Double}, {@link Float}).
 531  
      * @since 3.1
 532  
      */
 533  
     public static boolean isPrimitiveOrWrapper(final Class<?> type) {
 534  21
         if (type == null) {
 535  1
             return false;
 536  
         }
 537  20
         return type.isPrimitive() || isPrimitiveWrapper(type);
 538  
     }
 539  
 
 540  
     /**
 541  
      * Returns whether the given {@code type} is a primitive wrapper ({@link Boolean}, {@link Byte}, {@link Character}, {@link Short},
 542  
      * {@link Integer}, {@link Long}, {@link Double}, {@link Float}).
 543  
      * 
 544  
      * @param type
 545  
      *            The class to query or null.
 546  
      * @return true if the given {@code type} is a primitive wrapper ({@link Boolean}, {@link Byte}, {@link Character}, {@link Short},
 547  
      *         {@link Integer}, {@link Long}, {@link Double}, {@link Float}).
 548  
      * @since 3.1
 549  
      */
 550  
     public static boolean isPrimitiveWrapper(final Class<?> type) {
 551  32
         return wrapperPrimitiveMap.containsKey(type);
 552  
     }
 553  
 
 554  
     /**
 555  
      * <p>Checks if one {@code Class} can be assigned to a variable of
 556  
      * another {@code Class}.</p>
 557  
      *
 558  
      * <p>Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method,
 559  
      * this method takes into account widenings of primitive classes and
 560  
      * {@code null}s.</p>
 561  
      *
 562  
      * <p>Primitive widenings allow an int to be assigned to a long, float or
 563  
      * double. This method returns the correct result for these cases.</p>
 564  
      *
 565  
      * <p>{@code Null} may be assigned to any reference type. This method
 566  
      * will return {@code true} if {@code null} is passed in and the
 567  
      * toClass is non-primitive.</p>
 568  
      *
 569  
      * <p>Specifically, this method tests whether the type represented by the
 570  
      * specified {@code Class} parameter can be converted to the type
 571  
      * represented by this {@code Class} object via an identity conversion
 572  
      * widening primitive or widening reference conversion. See
 573  
      * <em><a href="http://java.sun.com/docs/books/jls/">The Java Language Specification</a></em>,
 574  
      * sections 5.1.1, 5.1.2 and 5.1.4 for details.</p>
 575  
      *
 576  
      * <p><strong>Since Lang 3.0,</strong> this method will default behavior for
 577  
      * calculating assignability between primitive and wrapper types <em>corresponding
 578  
      * to the running Java version</em>; i.e. autoboxing will be the default
 579  
      * behavior in VMs running Java versions >= 1.5.</p>
 580  
      *
 581  
      * @param cls  the Class to check, may be null
 582  
      * @param toClass  the Class to try to assign into, returns false if null
 583  
      * @return {@code true} if assignment possible
 584  
      */
 585  
     public static boolean isAssignable(final Class<?> cls, final Class<?> toClass) {
 586  257
         return isAssignable(cls, toClass, SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_5));
 587  
     }
 588  
 
 589  
     /**
 590  
      * <p>Checks if one {@code Class} can be assigned to a variable of
 591  
      * another {@code Class}.</p>
 592  
      *
 593  
      * <p>Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method,
 594  
      * this method takes into account widenings of primitive classes and
 595  
      * {@code null}s.</p>
 596  
      *
 597  
      * <p>Primitive widenings allow an int to be assigned to a long, float or
 598  
      * double. This method returns the correct result for these cases.</p>
 599  
      *
 600  
      * <p>{@code Null} may be assigned to any reference type. This method
 601  
      * will return {@code true} if {@code null} is passed in and the
 602  
      * toClass is non-primitive.</p>
 603  
      *
 604  
      * <p>Specifically, this method tests whether the type represented by the
 605  
      * specified {@code Class} parameter can be converted to the type
 606  
      * represented by this {@code Class} object via an identity conversion
 607  
      * widening primitive or widening reference conversion. See
 608  
      * <em><a href="http://java.sun.com/docs/books/jls/">The Java Language Specification</a></em>,
 609  
      * sections 5.1.1, 5.1.2 and 5.1.4 for details.</p>
 610  
      *
 611  
      * @param cls  the Class to check, may be null
 612  
      * @param toClass  the Class to try to assign into, returns false if null
 613  
      * @param autoboxing  whether to use implicit autoboxing/unboxing between primitives and wrappers
 614  
      * @return {@code true} if assignment possible
 615  
      */
 616  
     public static boolean isAssignable(Class<?> cls, final Class<?> toClass, final boolean autoboxing) {
 617  585
         if (toClass == null) {
 618  6
             return false;
 619  
         }
 620  
         // have to check for null, as isAssignableFrom doesn't
 621  579
         if (cls == null) {
 622  11
             return !toClass.isPrimitive();
 623  
         }
 624  
         //autoboxing:
 625  568
         if (autoboxing) {
 626  546
             if (cls.isPrimitive() && !toClass.isPrimitive()) {
 627  54
                 cls = primitiveToWrapper(cls);
 628  54
                 if (cls == null) {
 629  0
                     return false;
 630  
                 }
 631  
             }
 632  546
             if (toClass.isPrimitive() && !cls.isPrimitive()) {
 633  190
                 cls = wrapperToPrimitive(cls);
 634  190
                 if (cls == null) {
 635  0
                     return false;
 636  
                 }
 637  
             }
 638  
         }
 639  568
         if (cls.equals(toClass)) {
 640  65
             return true;
 641  
         }
 642  503
         if (cls.isPrimitive()) {
 643  249
             if (toClass.isPrimitive() == false) {
 644  6
                 return false;
 645  
             }
 646  243
             if (Integer.TYPE.equals(cls)) {
 647  24
                 return Long.TYPE.equals(toClass)
 648  
                     || Float.TYPE.equals(toClass)
 649  
                     || Double.TYPE.equals(toClass);
 650  
             }
 651  219
             if (Long.TYPE.equals(cls)) {
 652  36
                 return Float.TYPE.equals(toClass)
 653  
                     || Double.TYPE.equals(toClass);
 654  
             }
 655  183
             if (Boolean.TYPE.equals(cls)) {
 656  31
                 return false;
 657  
             }
 658  152
             if (Double.TYPE.equals(cls)) {
 659  26
                 return false;
 660  
             }
 661  126
             if (Float.TYPE.equals(cls)) {
 662  30
                 return Double.TYPE.equals(toClass);
 663  
             }
 664  96
             if (Character.TYPE.equals(cls)) {
 665  30
                 return Integer.TYPE.equals(toClass)
 666  
                     || Long.TYPE.equals(toClass)
 667  
                     || Float.TYPE.equals(toClass)
 668  
                     || Double.TYPE.equals(toClass);
 669  
             }
 670  66
             if (Short.TYPE.equals(cls)) {
 671  30
                 return Integer.TYPE.equals(toClass)
 672  
                     || Long.TYPE.equals(toClass)
 673  
                     || Float.TYPE.equals(toClass)
 674  
                     || Double.TYPE.equals(toClass);
 675  
             }
 676  36
             if (Byte.TYPE.equals(cls)) {
 677  36
                 return Short.TYPE.equals(toClass)
 678  
                     || Integer.TYPE.equals(toClass)
 679  
                     || Long.TYPE.equals(toClass)
 680  
                     || Float.TYPE.equals(toClass)
 681  
                     || Double.TYPE.equals(toClass);
 682  
             }
 683  
             // should never get here
 684  0
             return false;
 685  
         }
 686  254
         return toClass.isAssignableFrom(cls);
 687  
     }
 688  
 
 689  
     /**
 690  
      * <p>Converts the specified primitive Class object to its corresponding
 691  
      * wrapper Class object.</p>
 692  
      *
 693  
      * <p>NOTE: From v2.2, this method handles {@code Void.TYPE},
 694  
      * returning {@code Void.TYPE}.</p>
 695  
      *
 696  
      * @param cls  the class to convert, may be null
 697  
      * @return the wrapper class for {@code cls} or {@code cls} if
 698  
      * {@code cls} is not a primitive. {@code null} if null input.
 699  
      * @since 2.1
 700  
      */
 701  
     public static Class<?> primitiveToWrapper(final Class<?> cls) {
 702  101
         Class<?> convertedClass = cls;
 703  101
         if (cls != null && cls.isPrimitive()) {
 704  91
             convertedClass = primitiveWrapperMap.get(cls);
 705  
         }
 706  101
         return convertedClass;
 707  
     }
 708  
 
 709  
     /**
 710  
      * <p>Converts the specified array of primitive Class objects to an array of
 711  
      * its corresponding wrapper Class objects.</p>
 712  
      *
 713  
      * @param classes  the class array to convert, may be null or empty
 714  
      * @return an array which contains for each given class, the wrapper class or
 715  
      * the original class if class is not a primitive. {@code null} if null input.
 716  
      * Empty array if an empty array passed in.
 717  
      * @since 2.1
 718  
      */
 719  
     public static Class<?>[] primitivesToWrappers(final Class<?>... classes) {
 720  6
         if (classes == null) {
 721  1
             return null;
 722  
         }
 723  
 
 724  5
         if (classes.length == 0) {
 725  2
             return classes;
 726  
         }
 727  
 
 728  3
         final Class<?>[] convertedClasses = new Class[classes.length];
 729  17
         for (int i = 0; i < classes.length; i++) {
 730  14
             convertedClasses[i] = primitiveToWrapper(classes[i]);
 731  
         }
 732  3
         return convertedClasses;
 733  
     }
 734  
 
 735  
     /**
 736  
      * <p>Converts the specified wrapper class to its corresponding primitive
 737  
      * class.</p>
 738  
      *
 739  
      * <p>This method is the counter part of {@code primitiveToWrapper()}.
 740  
      * If the passed in class is a wrapper class for a primitive type, this
 741  
      * primitive type will be returned (e.g. {@code Integer.TYPE} for
 742  
      * {@code Integer.class}). For other classes, or if the parameter is
 743  
      * <b>null</b>, the return value is <b>null</b>.</p>
 744  
      *
 745  
      * @param cls the class to convert, may be <b>null</b>
 746  
      * @return the corresponding primitive type if {@code cls} is a
 747  
      * wrapper class, <b>null</b> otherwise
 748  
      * @see #primitiveToWrapper(Class)
 749  
      * @since 2.4
 750  
      */
 751  
     public static Class<?> wrapperToPrimitive(final Class<?> cls) {
 752  262
         return wrapperPrimitiveMap.get(cls);
 753  
     }
 754  
 
 755  
     /**
 756  
      * <p>Converts the specified array of wrapper Class objects to an array of
 757  
      * its corresponding primitive Class objects.</p>
 758  
      *
 759  
      * <p>This method invokes {@code wrapperToPrimitive()} for each element
 760  
      * of the passed in array.</p>
 761  
      *
 762  
      * @param classes  the class array to convert, may be null or empty
 763  
      * @return an array which contains for each given class, the primitive class or
 764  
      * <b>null</b> if the original class is not a wrapper class. {@code null} if null input.
 765  
      * Empty array if an empty array passed in.
 766  
      * @see #wrapperToPrimitive(Class)
 767  
      * @since 2.4
 768  
      */
 769  
     public static Class<?>[] wrappersToPrimitives(final Class<?>... classes) {
 770  5
         if (classes == null) {
 771  1
             return null;
 772  
         }
 773  
 
 774  4
         if (classes.length == 0) {
 775  2
             return classes;
 776  
         }
 777  
 
 778  2
         final Class<?>[] convertedClasses = new Class[classes.length];
 779  14
         for (int i = 0; i < classes.length; i++) {
 780  12
             convertedClasses[i] = wrapperToPrimitive(classes[i]);
 781  
         }
 782  2
         return convertedClasses;
 783  
     }
 784  
 
 785  
     // Inner class
 786  
     // ----------------------------------------------------------------------
 787  
     /**
 788  
      * <p>Is the specified class an inner class or static nested class.</p>
 789  
      *
 790  
      * @param cls  the class to check, may be null
 791  
      * @return {@code true} if the class is an inner or static nested class,
 792  
      *  false if not or {@code null}
 793  
      */
 794  
     public static boolean isInnerClass(final Class<?> cls) {
 795  6
         return cls != null && cls.getEnclosingClass() != null;
 796  
     }
 797  
 
 798  
     // Class loading
 799  
     // ----------------------------------------------------------------------
 800  
     /**
 801  
      * Returns the class represented by {@code className} using the
 802  
      * {@code classLoader}.  This implementation supports the syntaxes
 803  
      * "{@code java.util.Map.Entry[]}", "{@code java.util.Map$Entry[]}",
 804  
      * "{@code [Ljava.util.Map.Entry;}", and "{@code [Ljava.util.Map$Entry;}".
 805  
      *
 806  
      * @param classLoader  the class loader to use to load the class
 807  
      * @param className  the class name
 808  
      * @param initialize  whether the class must be initialized
 809  
      * @return the class represented by {@code className} using the {@code classLoader}
 810  
      * @throws ClassNotFoundException if the class is not found
 811  
      */
 812  
     public static Class<?> getClass(
 813  
             final ClassLoader classLoader, final String className, final boolean initialize) throws ClassNotFoundException {
 814  
         try {
 815  
             Class<?> clazz;
 816  78
             if (abbreviationMap.containsKey(className)) {
 817  8
                 final String clsName = "[" + abbreviationMap.get(className);
 818  8
                 clazz = Class.forName(clsName, initialize, classLoader).getComponentType();
 819  8
             } else {
 820  70
                 clazz = Class.forName(toCanonicalName(className), initialize, classLoader);
 821  
             }
 822  56
             return clazz;
 823  21
         } catch (final ClassNotFoundException ex) {
 824  
             // allow path separators (.) as inner class name separators
 825  21
             final int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
 826  
 
 827  21
             if (lastDotIndex != -1) {
 828  
                 try {
 829  12
                     return getClass(classLoader, className.substring(0, lastDotIndex) +
 830  
                             INNER_CLASS_SEPARATOR_CHAR + className.substring(lastDotIndex + 1),
 831  
                             initialize);
 832  6
                 } catch (final ClassNotFoundException ex2) { // NOPMD
 833  
                     // ignore exception
 834  
                 }
 835  
             }
 836  
 
 837  15
             throw ex;
 838  
         }
 839  
     }
 840  
 
 841  
     /**
 842  
      * Returns the (initialized) class represented by {@code className}
 843  
      * using the {@code classLoader}.  This implementation supports
 844  
      * the syntaxes "{@code java.util.Map.Entry[]}",
 845  
      * "{@code java.util.Map$Entry[]}", "{@code [Ljava.util.Map.Entry;}",
 846  
      * and "{@code [Ljava.util.Map$Entry;}".
 847  
      *
 848  
      * @param classLoader  the class loader to use to load the class
 849  
      * @param className  the class name
 850  
      * @return the class represented by {@code className} using the {@code classLoader}
 851  
      * @throws ClassNotFoundException if the class is not found
 852  
      */
 853  
     public static Class<?> getClass(final ClassLoader classLoader, final String className) throws ClassNotFoundException {
 854  0
         return getClass(classLoader, className, true);
 855  
     }
 856  
 
 857  
     /**
 858  
      * Returns the (initialized) class represented by {@code className}
 859  
      * using the current thread's context class loader. This implementation
 860  
      * supports the syntaxes "{@code java.util.Map.Entry[]}",
 861  
      * "{@code java.util.Map$Entry[]}", "{@code [Ljava.util.Map.Entry;}",
 862  
      * and "{@code [Ljava.util.Map$Entry;}".
 863  
      *
 864  
      * @param className  the class name
 865  
      * @return the class represented by {@code className} using the current thread's context class loader
 866  
      * @throws ClassNotFoundException if the class is not found
 867  
      */
 868  
     public static Class<?> getClass(final String className) throws ClassNotFoundException {
 869  66
         return getClass(className, true);
 870  
     }
 871  
 
 872  
     /**
 873  
      * Returns the class represented by {@code className} using the
 874  
      * current thread's context class loader. This implementation supports the
 875  
      * syntaxes "{@code java.util.Map.Entry[]}", "{@code java.util.Map$Entry[]}",
 876  
      * "{@code [Ljava.util.Map.Entry;}", and "{@code [Ljava.util.Map$Entry;}".
 877  
      *
 878  
      * @param className  the class name
 879  
      * @param initialize  whether the class must be initialized
 880  
      * @return the class represented by {@code className} using the current thread's context class loader
 881  
      * @throws ClassNotFoundException if the class is not found
 882  
      */
 883  
     public static Class<?> getClass(final String className, final boolean initialize) throws ClassNotFoundException {
 884  66
         final ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
 885  66
         final ClassLoader loader = contextCL == null ? ClassUtils.class.getClassLoader() : contextCL;
 886  66
         return getClass(loader, className, initialize);
 887  
     }
 888  
 
 889  
     // Public method
 890  
     // ----------------------------------------------------------------------
 891  
     /**
 892  
      * <p>Returns the desired Method much like {@code Class.getMethod}, however
 893  
      * it ensures that the returned Method is from a public class or interface and not
 894  
      * from an anonymous inner class. This means that the Method is invokable and
 895  
      * doesn't fall foul of Java bug
 896  
      * <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4071957">4071957</a>).
 897  
      *
 898  
      *  <code><pre>Set set = Collections.unmodifiableSet(...);
 899  
      *  Method method = ClassUtils.getPublicMethod(set.getClass(), "isEmpty",  new Class[0]);
 900  
      *  Object result = method.invoke(set, new Object[]);</pre></code>
 901  
      * </p>
 902  
      *
 903  
      * @param cls  the class to check, not null
 904  
      * @param methodName  the name of the method
 905  
      * @param parameterTypes  the list of parameters
 906  
      * @return the method
 907  
      * @throws NullPointerException if the class is null
 908  
      * @throws SecurityException if a security violation occurred
 909  
      * @throws NoSuchMethodException if the method is not found in the given class
 910  
      *  or if the metothod doen't conform with the requirements
 911  
      */
 912  
     public static Method getPublicMethod(final Class<?> cls, final String methodName, final Class<?>... parameterTypes)
 913  
             throws SecurityException, NoSuchMethodException {
 914  
 
 915  2
         final Method declaredMethod = cls.getMethod(methodName, parameterTypes);
 916  2
         if (Modifier.isPublic(declaredMethod.getDeclaringClass().getModifiers())) {
 917  1
             return declaredMethod;
 918  
         }
 919  
 
 920  1
         final List<Class<?>> candidateClasses = new ArrayList<Class<?>>();
 921  1
         candidateClasses.addAll(getAllInterfaces(cls));
 922  1
         candidateClasses.addAll(getAllSuperclasses(cls));
 923  
 
 924  1
         for (final Class<?> candidateClass : candidateClasses) {
 925  1
             if (!Modifier.isPublic(candidateClass.getModifiers())) {
 926  0
                 continue;
 927  
             }
 928  
             Method candidateMethod;
 929  
             try {
 930  1
                 candidateMethod = candidateClass.getMethod(methodName, parameterTypes);
 931  0
             } catch (final NoSuchMethodException ex) {
 932  0
                 continue;
 933  1
             }
 934  1
             if (Modifier.isPublic(candidateMethod.getDeclaringClass().getModifiers())) {
 935  1
                 return candidateMethod;
 936  
             }
 937  0
         }
 938  
 
 939  0
         throw new NoSuchMethodException("Can't find a public method for " +
 940  
                 methodName + " " + ArrayUtils.toString(parameterTypes));
 941  
     }
 942  
 
 943  
     // ----------------------------------------------------------------------
 944  
     /**
 945  
      * Converts a class name to a JLS style class name.
 946  
      *
 947  
      * @param className  the class name
 948  
      * @return the converted name
 949  
      */
 950  
     private static String toCanonicalName(String className) {
 951  70
         className = StringUtils.deleteWhitespace(className);
 952  70
         if (className == null) {
 953  1
             throw new NullPointerException("className must not be null.");
 954  69
         } else if (className.endsWith("[]")) {
 955  29
             final StringBuilder classNameBuffer = new StringBuilder();
 956  69
             while (className.endsWith("[]")) {
 957  40
                 className = className.substring(0, className.length() - 2);
 958  40
                 classNameBuffer.append("[");
 959  
             }
 960  29
             final String abbreviation = abbreviationMap.get(className);
 961  29
             if (abbreviation != null) {
 962  20
                 classNameBuffer.append(abbreviation);
 963  
             } else {
 964  9
                 classNameBuffer.append("L").append(className).append(";");
 965  
             }
 966  29
             className = classNameBuffer.toString();
 967  
         }
 968  69
         return className;
 969  
     }
 970  
 
 971  
     /**
 972  
      * <p>Converts an array of {@code Object} in to an array of {@code Class} objects.
 973  
      * If any of these objects is null, a null element will be inserted into the array.</p>
 974  
      *
 975  
      * <p>This method returns {@code null} for a {@code null} input array.</p>
 976  
      *
 977  
      * @param array an {@code Object} array
 978  
      * @return a {@code Class} array, {@code null} if null array input
 979  
      * @since 2.4
 980  
      */
 981  
     public static Class<?>[] toClass(final Object... array) {
 982  69
         if (array == null) {
 983  1
             return null;
 984  68
         } else if (array.length == 0) {
 985  18
             return ArrayUtils.EMPTY_CLASS_ARRAY;
 986  
         }
 987  50
         final Class<?>[] classes = new Class[array.length];
 988  104
         for (int i = 0; i < array.length; i++) {
 989  54
             classes[i] = array[i] == null ? null : array[i].getClass();
 990  
         }
 991  50
         return classes;
 992  
     }
 993  
 
 994  
     // Short canonical name
 995  
     // ----------------------------------------------------------------------
 996  
     /**
 997  
      * <p>Gets the canonical name minus the package name for an {@code Object}.</p>
 998  
      *
 999  
      * @param object  the class to get the short name for, may be null
 1000  
      * @param valueIfNull  the value to return if null
 1001  
      * @return the canonical name of the object without the package name, or the null value
 1002  
      * @since 2.4
 1003  
      */
 1004  
     public static String getShortCanonicalName(final Object object, final String valueIfNull) {
 1005  9
         if (object == null) {
 1006  1
             return valueIfNull;
 1007  
         }
 1008  8
         return getShortCanonicalName(object.getClass().getName());
 1009  
     }
 1010  
 
 1011  
     /**
 1012  
      * <p>Gets the canonical name minus the package name from a {@code Class}.</p>
 1013  
      *
 1014  
      * @param cls  the class to get the short name for.
 1015  
      * @return the canonical name without the package name or an empty string
 1016  
      * @since 2.4
 1017  
      */
 1018  
     public static String getShortCanonicalName(final Class<?> cls) {
 1019  8
         if (cls == null) {
 1020  0
             return StringUtils.EMPTY;
 1021  
         }
 1022  8
         return getShortCanonicalName(cls.getName());
 1023  
     }
 1024  
 
 1025  
     /**
 1026  
      * <p>Gets the canonical name minus the package name from a String.</p>
 1027  
      *
 1028  
      * <p>The string passed in is assumed to be a canonical name - it is not checked.</p>
 1029  
      *
 1030  
      * @param canonicalName  the class name to get the short name for
 1031  
      * @return the canonical name of the class without the package name or an empty string
 1032  
      * @since 2.4
 1033  
      */
 1034  
     public static String getShortCanonicalName(final String canonicalName) {
 1035  28
         return ClassUtils.getShortClassName(getCanonicalName(canonicalName));
 1036  
     }
 1037  
 
 1038  
     // Package name
 1039  
     // ----------------------------------------------------------------------
 1040  
     /**
 1041  
      * <p>Gets the package name from the canonical name of an {@code Object}.</p>
 1042  
      *
 1043  
      * @param object  the class to get the package name for, may be null
 1044  
      * @param valueIfNull  the value to return if null
 1045  
      * @return the package name of the object, or the null value
 1046  
      * @since 2.4
 1047  
      */
 1048  
     public static String getPackageCanonicalName(final Object object, final String valueIfNull) {
 1049  9
         if (object == null) {
 1050  1
             return valueIfNull;
 1051  
         }
 1052  8
         return getPackageCanonicalName(object.getClass().getName());
 1053  
     }
 1054  
 
 1055  
     /**
 1056  
      * <p>Gets the package name from the canonical name of a {@code Class}.</p>
 1057  
      *
 1058  
      * @param cls  the class to get the package name for, may be {@code null}.
 1059  
      * @return the package name or an empty string
 1060  
      * @since 2.4
 1061  
      */
 1062  
     public static String getPackageCanonicalName(final Class<?> cls) {
 1063  8
         if (cls == null) {
 1064  0
             return StringUtils.EMPTY;
 1065  
         }
 1066  8
         return getPackageCanonicalName(cls.getName());
 1067  
     }
 1068  
 
 1069  
     /**
 1070  
      * <p>Gets the package name from the canonical name. </p>
 1071  
      *
 1072  
      * <p>The string passed in is assumed to be a canonical name - it is not checked.</p>
 1073  
      * <p>If the class is unpackaged, return an empty string.</p>
 1074  
      *
 1075  
      * @param canonicalName  the canonical name to get the package name for, may be {@code null}
 1076  
      * @return the package name or an empty string
 1077  
      * @since 2.4
 1078  
      */
 1079  
     public static String getPackageCanonicalName(final String canonicalName) {
 1080  28
         return ClassUtils.getPackageName(getCanonicalName(canonicalName));
 1081  
     }
 1082  
 
 1083  
     /**
 1084  
      * <p>Converts a given name of class into canonical format.
 1085  
      * If name of class is not a name of array class it returns
 1086  
      * unchanged name.</p>
 1087  
      * <p>Example:
 1088  
      * <ul>
 1089  
      * <li>{@code getCanonicalName("[I") = "int[]"}</li>
 1090  
      * <li>{@code getCanonicalName("[Ljava.lang.String;") = "java.lang.String[]"}</li>
 1091  
      * <li>{@code getCanonicalName("java.lang.String") = "java.lang.String"}</li>
 1092  
      * </ul>
 1093  
      * </p>
 1094  
      *
 1095  
      * @param className the name of class
 1096  
      * @return canonical form of class name
 1097  
      * @since 2.4
 1098  
      */
 1099  
     private static String getCanonicalName(String className) {
 1100  56
         className = StringUtils.deleteWhitespace(className);
 1101  56
         if (className == null) {
 1102  0
             return null;
 1103  
         } else {
 1104  56
             int dim = 0;
 1105  92
             while (className.startsWith("[")) {
 1106  36
                 dim++;
 1107  36
                 className = className.substring(1);
 1108  
             }
 1109  56
             if (dim < 1) {
 1110  32
                 return className;
 1111  
             } else {
 1112  24
                 if (className.startsWith("L")) {
 1113  12
                     className = className.substring(
 1114  
                         1,
 1115  
                         className.endsWith(";")
 1116  
                             ? className.length() - 1
 1117  
                             : className.length());
 1118  
                 } else {
 1119  12
                     if (className.length() > 0) {
 1120  12
                         className = reverseAbbreviationMap.get(className.substring(0, 1));
 1121  
                     }
 1122  
                 }
 1123  24
                 final StringBuilder canonicalClassNameBuffer = new StringBuilder(className);
 1124  60
                 for (int i = 0; i < dim; i++) {
 1125  36
                     canonicalClassNameBuffer.append("[]");
 1126  
                 }
 1127  24
                 return canonicalClassNameBuffer.toString();
 1128  
             }
 1129  
         }
 1130  
     }
 1131  
 
 1132  
 }