View Javadoc

1   /*
2    *  Copyright 2005-2006 Stefan Reuter
3    *
4    *  Licensed under the Apache License, Version 2.0 (the "License");
5    *  you may not use this file except in compliance with the License.
6    *  You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *  Unless required by applicable law or agreed to in writing, software
11   *  distributed under the License is distributed on an "AS IS" BASIS,
12   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *  See the License for the specific language governing permissions and
14   *  limitations under the License.
15   *
16   */
17  package org.asteriskjava.util;
18  
19  import java.lang.reflect.Method;
20  import java.lang.reflect.Constructor;
21  import java.lang.reflect.InvocationTargetException;
22  import java.util.HashMap;
23  import java.util.Locale;
24  import java.util.Map;
25  
26  /**
27   * Utility class that provides helper methods for reflection that is used by the
28   * fastagi and manager packages to access getter and setter methods.<p>
29   * Client code is not supposed to use this class.
30   *
31   * @author srt
32   */
33  public class ReflectionUtil
34  {
35      private ReflectionUtil()
36      {
37          // hide constructor
38      }
39  
40      /**
41       * Returns a Map of getter methods of the given class.<p>
42       * The key of the map contains the name of the attribute that can be
43       * accessed by the getter, the value the getter itself (an instance of
44       * java.lang.reflect.Method). A method is considered a getter if its name
45       * starts with "get", it is declared public and takes no arguments.
46       *
47       * @param clazz the class to return the getters for
48       * @return a Map of attributes and their accessor methods (getters)
49       */
50      public static Map<String, Method> getGetters(final Class<?> clazz)
51      {
52          final Map<String, Method> accessors = new HashMap<String, Method>();
53          final Method[] methods = clazz.getMethods();
54  
55          for (Method method : methods)
56          {
57              String name;
58              String methodName;
59  
60              methodName = method.getName();
61              if (!methodName.startsWith("get"))
62              {
63                  continue;
64              }
65  
66              // skip methods with != 0 parameters
67              if (method.getParameterTypes().length != 0)
68              {
69                  continue;
70              }
71  
72              // ok seems to be an accessor
73              name = methodName.substring("get".length()).toLowerCase(Locale.ENGLISH);
74  
75              if (name.length() == 0)
76              {
77                  continue;
78              }
79  
80              accessors.put(name, method);
81          }
82  
83          return accessors;
84      }
85  
86      /**
87       * Returns a Map of setter methods of the given class.<p>
88       * The key of the map contains the name of the attribute that can be
89       * accessed by the setter, the value the setter itself (an instance of
90       * java.lang.reflect.Method). A method is considered a setter if its name
91       * starts with "set", it is declared public and takes exactly one argument.
92       *
93       * @param clazz the class to return the setters for
94       * @return a Map of attributes and their accessor methods (setters)
95       */
96      public static Map<String, Method> getSetters(Class<?> clazz)
97      {
98          final Map<String, Method> accessors = new HashMap<String, Method>();
99          final Method[] methods = clazz.getMethods();
100 
101         for (Method method : methods)
102         {
103             String name;
104             String methodName;
105 
106             methodName = method.getName();
107             if (!methodName.startsWith("set"))
108             {
109                 continue;
110             }
111 
112             // skip methods with != 1 parameters
113             if (method.getParameterTypes().length != 1)
114             {
115                 continue;
116             }
117 
118             // ok seems to be an accessor
119             name = methodName.substring("set".length()).toLowerCase(Locale.US);
120             accessors.put(name, method);
121         }
122 
123         return accessors;
124     }
125 
126 
127     /**
128      * Strips all illegal charaters from the given lower case string.
129      * Illegal characters are all characters that are neither characters ('a' to 'z') nor digits ('0' to '9').
130      *
131      * @param s the original string
132      * @return the string with all illegal characters stripped
133      */
134     public static String stripIllegalCharacters(String s)
135     {
136         char c;
137         boolean needsStrip = false;
138         StringBuffer sb;
139 
140         if (s == null)
141         {
142             return null;
143         }
144 
145         for (int i = 0; i < s.length(); i++)
146         {
147             c = s.charAt(i);
148             if (c >= '0' && c <= '9')
149             {
150                 // continue
151             } // NOPMD
152             else if (c >= 'a' && c <= 'z')
153             {
154                 // continue
155             } // NOPMD
156             else
157             {
158                 needsStrip = true;
159                 break;
160             }
161         }
162 
163         if (!needsStrip)
164         {
165             return s;
166         }
167 
168         sb = new StringBuffer(s.length());
169         for (int i = 0; i < s.length(); i++)
170         {
171             c = s.charAt(i);
172             if (c >= '0' && c <= '9')
173             {
174                 sb.append(c);
175             }
176             else if (c >= 'a' && c <= 'z')
177             {
178                 sb.append(c);
179             }
180         }
181 
182         return sb.toString();
183     }
184 
185     /**
186      * Checks if the class is available on the current thread's context class loader.
187      *
188      * @param s fully qualified name of the class to check.
189      * @return <code>true</code> if the class is available, <code>false</code> otherwise.
190      */
191     public static boolean isClassAvailable(String s)
192     {
193         final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
194 
195         try
196         {
197             classLoader.loadClass(s);
198             return true;
199         }
200         catch (ClassNotFoundException e)
201         {
202             return false;
203         }
204     }
205 
206     /**
207      * Creates a new instance of the given class. The class is loaded using the current thread's context
208      * class loader and instantiated using its default constructor.
209      *
210      * @param s fully qualified name of the class to instantiate.
211      * @return the new instance or <code>null</code> on failure.
212      */
213     public static Object newInstance(String s)
214     {
215         final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
216 
217         try
218         {
219             Class<?> clazz = classLoader.loadClass(s);
220             Constructor<?> constructor = clazz.getConstructor();
221             return constructor.newInstance();
222         }
223         catch (ClassNotFoundException e)
224         {
225             return null;
226         }
227         catch (IllegalAccessException e)
228         {
229             return null;
230         }
231         catch (InstantiationException e)
232         {
233             return null;
234         }
235         catch (NoSuchMethodException e)
236         {
237             // no default constructor
238             return null;
239         }
240         catch (InvocationTargetException e)
241         {
242             // constructor threw an exception
243             return null;
244         }
245     }
246 }