Java ClassPath Get getClassFromLibs(String className, List libs, boolean useSystemClassPath)

Here you can find the source of getClassFromLibs(String className, List libs, boolean useSystemClassPath)

Description

get Class From Libs

License

Apache License

Declaration

public static <T> Class<T> getClassFromLibs(String className, List<String> libs, boolean useSystemClassPath)
            throws ClassNotFoundException 

Method Source Code


//package com.java2s;
/*/*from w  w w  .  j  ava2s  . c  o m*/
 * Copyright 2014 Lukas Benda <lbenda at lbenda.cz>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.File;

import java.net.*;
import java.util.*;

public class Main {
    public static <T> Class<T> getClassFromLibs(String className, List<String> libs, boolean useSystemClassPath)
            throws ClassNotFoundException {
        ClassLoader clr = createClassLoader(libs, useSystemClassPath);
        //noinspection unchecked
        return (Class<T>) clr.loadClass(className);
    }

    public static ClassLoader createClassLoader(List<String> libs, boolean useSystemClassPath) {
        List<URL> urls = new ArrayList<>(libs.size());
        libs.forEach(lib -> {
            try {
                urls.add((new File(lib)).toURI().toURL());
            } catch (MalformedURLException e) {
                throw new RuntimeException("The file wasn't readable: " + lib, e);
            }
        });

        URLClassLoader urlCl;
        if (useSystemClassPath) {
            urlCl = new URLClassLoader(urls.toArray(new URL[urls.size()]), System.class.getClassLoader());
        } else {
            urlCl = new URLClassLoader(urls.toArray(new URL[urls.size()]));
        }
        return urlCl;
    }
}

Related

  1. getClassLoaderClasspath(ClassLoader loader)
  2. getClassPath()
  3. getClasspath()
  4. getClasspath()