View Javadoc
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  
18  package org.apache.commons.jxpath.util;
19  
20  import java.util.HashMap;
21  import java.util.Map;
22  import java.util.Objects;
23  
24  /**
25   * Port of class loading methods from {@code org.apache.commons.lang3.ClassUtils} from the Apache Commons Lang Component. Some adjustments made to remove
26   * dependency on {@code org.apache.commons.lang3.StringUtils}. Also modified to fall back on the current class loader when an attempt to load a class with the
27   * context class loader results in a {@code java.lang.ClassNotFoundException}.
28   *
29   * See org.apache.commons.lang3.ClassUtils
30   * @since 1.4.0
31   */
32  public final class ClassLoaderUtil {
33  
34      /**
35       * Maps a primitive class name to its corresponding abbreviation used in array class names.
36       */
37      private static Map<String, String> abbreviationMap = new HashMap<>();
38      /**
39       * Feed abbreviation maps
40       */
41      static {
42          addAbbreviation("int", "I");
43          addAbbreviation("boolean", "Z");
44          addAbbreviation("float", "F");
45          addAbbreviation("long", "J");
46          addAbbreviation("short", "S");
47          addAbbreviation("byte", "B");
48          addAbbreviation("double", "D");
49          addAbbreviation("char", "C");
50      }
51  
52      /**
53       * Adds primitive type abbreviation to map of abbreviations.
54       *
55       * @param primitive    Canonical name of primitive type
56       * @param abbreviation Corresponding abbreviation of primitive type
57       */
58      private static void addAbbreviation(final String primitive, final String abbreviation) {
59          abbreviationMap.put(primitive, abbreviation);
60      }
61  
62      /**
63       * Gets the class represented by {@code className} using the {@code classLoader}. This implementation supports names like "{@code java.lang.String[]}" as
64       * well as "{@code [Ljava.lang.String;}".
65       *
66       * @param <T> The expected class type.
67       * @param classLoader the class loader to use to load the class
68       * @param className   the class name
69       * @param initialize  whether the class must be initialized
70       * @return the class represented by {@code className} using the {@code classLoader}
71       * @throws ClassNotFoundException if the class is not found
72       */
73      @SuppressWarnings("unchecked") // assume the call site knows what it's doing.
74      private static <T> Class<T> getClass(final ClassLoader classLoader, final String className, final boolean initialize) throws ClassNotFoundException {
75          Class<T> clazz;
76          if (abbreviationMap.containsKey(className)) {
77              final String clsName = "[" + abbreviationMap.get(className);
78              clazz = (Class<T>) Class.forName(clsName, initialize, classLoader).getComponentType();
79          } else {
80              clazz = (Class<T>) Class.forName(toCanonicalName(className), initialize, classLoader);
81          }
82          return clazz;
83      }
84  
85      /**
86       * Gets the class represented by {@code className} using the current thread's context class loader. This implementation supports names like
87       * "{@code java.lang.String[]}" as well as "{@code [Ljava.lang.String;}".
88       *
89       * @param <T> The expected class type.
90       * @param className  the class name
91       * @param initialize whether the class must be initialized
92       * @return the class represented by {@code className} using the current thread's context class loader
93       * @throws ClassNotFoundException if the class is not found
94       */
95      public static <T> Class<T> getClass(final String className, final boolean initialize) throws ClassNotFoundException {
96          final ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
97          final ClassLoader currentCL = ClassLoaderUtil.class.getClassLoader();
98          if (contextCL != null) {
99              try {
100                 return getClass(contextCL, className, initialize);
101             } catch (final ClassNotFoundException ignore) { // NOPMD
102                 // ignore this exception and try the current class loader
103             }
104         }
105         return getClass(currentCL, className, initialize);
106     }
107 
108     /**
109      * Converts a class name to a JLS style class name.
110      *
111      * @param className the class name
112      * @return the converted name
113      */
114     private static String toCanonicalName(String className) {
115         Objects.requireNonNull(className, "className");
116         if (className.endsWith("[]")) {
117             final StringBuilder classNameBuffer = new StringBuilder();
118             while (className.endsWith("[]")) {
119                 className = className.substring(0, className.length() - 2);
120                 classNameBuffer.append("[");
121             }
122             final String abbreviation = abbreviationMap.get(className);
123             if (abbreviation != null) {
124                 classNameBuffer.append(abbreviation);
125             } else {
126                 classNameBuffer.append("L").append(className).append(";");
127             }
128             className = classNameBuffer.toString();
129         }
130         return className;
131     }
132 
133     /**
134      * New need to constructs new instances.
135      */
136     private ClassLoaderUtil() {
137         // empty
138     }
139 }