Java Jar File Load loadClassesFromJar(final String jarPath, final CharSequence matchingPath)

Here you can find the source of loadClassesFromJar(final String jarPath, final CharSequence matchingPath)

Description

load Classes From Jar

License

Open Source License

Declaration

static List<Class<?>> loadClassesFromJar(final String jarPath, final CharSequence matchingPath) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class Main {
    static final String CLASS_FILE_EXTENSION = ".class";

    static List<Class<?>> loadClassesFromJar(final String jarPath, final CharSequence matchingPath) {
        List<Class<?>> classes = new ArrayList<>();

        try {/*from   w w w  .  jav a2s  .  c  o m*/
            JarFile jarFile = new JarFile(jarPath);
            Enumeration<JarEntry> jarEntries = jarFile.entries();

            URLClassLoader cl = URLClassLoader.newInstance(new URL[] { new URL("jar:file:" + jarPath + "!/") });

            while (jarEntries.hasMoreElements()) {
                JarEntry jarEntry = jarEntries.nextElement();

                if (jarEntry.isDirectory() || !jarEntry.toString().contains(matchingPath)
                        || !jarEntry.getName().endsWith(CLASS_FILE_EXTENSION)) {
                    continue;
                }

                String className = jarEntry.getName().substring(0, jarEntry.getName().length() - 6).replace('/',
                        '.');
                classes.add(cl.loadClass(className));
            }
        } catch (Exception e) {
            return Collections.EMPTY_LIST;
        }

        return classes;
    }
}

Related

  1. loadClassFromJar(String jarAbsolutePath, String className)
  2. loadJar(File jar)
  3. loadJar(String jarPath)
  4. loadJar(String path)