简体   繁体   中英

Dynamic Class Loading From Jar File

I have been trying to figure out how to dynamically load classes from a jar file during runtime, knowing the name of the package to load them from. I have tried this: How to get all classes names in a package? It didnt work, I later realized it was for programs outside of jar files. I also took this snippet of code from another question, which I like a lot more:

URL[] urls = ....
URLClassLoader loader = new URLClassLoader(urls);
Class<?> cls = loader.loadClass("com.example.core.Main");
Module module = (Module) cls.newInstance();

But I don't see a way to load all classes in a defined package, like

Class<?>[] cls = loader.loadPackage("com.example.core");

How is this best solved? I have researched quite a bit and thought I was going at it the wrong way perhaps. Ultimately I just want to load all the classes in a package, without knowing anything but the package name, for an easier "Drop the class in" editing method.

This is technically feasible as follows:

private List<Class<?>> loadClassesInPackage(String packageName) {

    ClassLoader loader = getClassLoader();
    List<Class<?>> list = new ArrayList<Class<?>>();
    // com\.package\.subpackage(?!.*\$).*
    String regex = Pattern.quote(packageName) + "(?!.*\\$).*";

    try {
        DexFile df = new DexFile(getPackageCodePath());
        for (Enumeration<String> e = df.entries(); e.hasMoreElements(); ) {
            String s = e.nextElement();

            if (s.matches(regex)) {
                Log.d(TAG, "match: " + s);

                list.add(loader.loadClass(s));
            }

        }
    } catch (Exception e) {
        Log.w(TAG, "exception while building class list", e);
    }

    return list;
}

It will exclude inner/anonymous classes as it is. Also, there are plenty of caveats, such as loading classes without default constructors, abstract classes, etc. This should work for any class that exists in your app's APK, including library references.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM