Java Jar File Load loadJarFile(File jarFile, String className)

Here you can find the source of loadJarFile(File jarFile, String className)

Description

Loads class className from the jar file jarFile.

License

Open Source License

Parameter

Parameter Description
jarFile jar file to search
className class name to load

Exception

Parameter Description
Exception if any problem

Return

new class instance

Declaration

@SuppressWarnings("unchecked")
public static final <T> T loadJarFile(File jarFile, String className) throws Exception 

Method Source Code

//package com.java2s;
/*//w  w w .jav a2s. c  om
 * BeanGenerator
 * 
 * Copyright (C) 2011 galaxyworld.org
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.File;

import java.net.URL;
import java.net.URLClassLoader;

public class Main {
    /**
     * Loads class <i>className</i> from the jar file <i>jarFile</i>.
     * 
     * @param jarFile jar file to search
     * @param className class name to load
     * @return new class instance
     * @throws Exception if any problem
     */
    @SuppressWarnings("unchecked")
    public static final <T> T loadJarFile(File jarFile, String className) throws Exception {
        URL[] urls = new URL[] { jarFile.toURI().toURL() };
        URLClassLoader classLoader = new URLClassLoader(urls, Thread.currentThread().getContextClassLoader());
        Class<?> cls = classLoader.loadClass(className);
        return (T) cls.newInstance();
    }
}

Related

  1. loadClassesFromJar(final String jarPath, final CharSequence matchingPath)
  2. loadClassFromJar(String jarAbsolutePath, String className)
  3. loadJar(File jar)
  4. loadJar(String jarPath)
  5. loadJar(String path)
  6. loadJarInSystemClassLoader(File out)
  7. loadJarIntoClasspath(File jarFile)
  8. loadJarsFromDir(final File dir)