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