1 /*
2 * Copyright 2012 Christopher Pheby
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 * http://www.apache.org/licenses/LICENSE-2.0
7 * Unless required by applicable law or agreed to in writing, software
8 * distributed under the License is distributed on an "AS IS" BASIS,
9 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 * See the License for the specific language governing permissions and
11 * limitations under the License.
12 */
13 package org.jadira.scanner.core.utils.reflection;
14
15 /**
16 * Utility methods related to {@link ClassLoader} resolution and the like
17 */
18 public final class ClassLoaderUtils {
19
20 private ClassLoaderUtils() {
21 }
22
23 /**
24 * Gets {@link ClassLoader} for the current thread
25 * @param classLoaders ClassLoaders to be used if specified
26 * @return The ClassLoaders, either those specified, or discovered
27 * ClassLoaders for the current thread
28 */
29 public static ClassLoader[] getClassLoaders(ClassLoader... classLoaders) {
30
31 if (classLoaders != null && classLoaders.length > 0) {
32 return classLoaders;
33 }
34
35 final ClassLoader ctxClassLoader = Thread.currentThread()
36 .getContextClassLoader();
37 final ClassLoader staticClassLoader = ClassLoaderUtils.class
38 .getClassLoader();
39
40 if (ctxClassLoader == null) {
41 if (staticClassLoader == null) {
42 return new ClassLoader[] {};
43 } else {
44 return new ClassLoader[] { staticClassLoader };
45 }
46 } else {
47 if (staticClassLoader == null) {
48 return new ClassLoader[] { ctxClassLoader };
49 } else {
50 return new ClassLoader[] { ctxClassLoader, staticClassLoader };
51 }
52 }
53 }
54
55 /**
56 * Attempts to instantiate the named class, using each of the specified
57 * ClassLoaders in turn or Class.forName if these do not work
58 * @param name The class name
59 * @param classLoaders ClassLoaders to be used
60 * @return The Class instance
61 * @throws ClassNotFoundException If the class cannot be found
62 */
63 public static Class<?> classForName(String name,
64 ClassLoader... classLoaders) throws ClassNotFoundException {
65
66 ClassLoader[] cls = getClassLoaders(classLoaders);
67
68 for (ClassLoader cl : cls) {
69 try {
70 if (cl != null) {
71 return cl.loadClass(name);
72 }
73 } catch (ClassNotFoundException e) {
74 // Ignore
75 }
76 }
77 // Try using Class.forName()
78 return Class.forName(name);
79 }
80 }