View Javadoc
1   /*
2    *    Copyright 2006-2023 the original author or authors.
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    *       https://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  package org.mybatis.generator.internal.util;
17  
18  import static org.mybatis.generator.internal.util.messages.Messages.getString;
19  
20  import java.io.File;
21  import java.net.MalformedURLException;
22  import java.net.URL;
23  import java.net.URLClassLoader;
24  import java.util.ArrayList;
25  import java.util.Collection;
26  import java.util.List;
27  
28  import org.mybatis.generator.logging.Log;
29  import org.mybatis.generator.logging.LogFactory;
30  
31  /**
32   * This class holds methods useful for constructing custom classloaders.
33   *
34   * @author Jeff Butler
35   */
36  public class ClassloaderUtility {
37  
38      private static final Log LOG = LogFactory.getLog(ClassloaderUtility.class);
39  
40      /**
41       * Utility Class - No Instances.
42       */
43      private ClassloaderUtility() {
44      }
45  
46      public static ClassLoader getCustomClassloader(Collection<String> entries) {
47          List<URL> urls = new ArrayList<>();
48          File file;
49  
50          if (entries != null) {
51              for (String classPathEntry : entries) {
52                  file = new File(classPathEntry);
53                  if (!file.exists()) {
54                      LOG.warn(getString("Warning.31", classPathEntry)); //$NON-NLS-1$
55                      continue;
56                  }
57  
58                  try {
59                      urls.add(file.toURI().toURL());
60                  } catch (MalformedURLException e) {
61                      // this shouldn't happen, but just in case...
62                      throw new RuntimeException(getString(
63                              "RuntimeError.9", classPathEntry)); //$NON-NLS-1$
64                  }
65              }
66          }
67  
68          ClassLoader parent = Thread.currentThread().getContextClassLoader();
69  
70          return new URLClassLoader(urls.toArray(new URL[urls.size()]), parent);
71      }
72  }