Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically load classes from other APK's

I am creating a framework to be used by many departments in my work environment. I need a way to dynamically load classes into the framework from individual department apk's. For instance a way to dynamically load department A's content provider class into the framework.

I have had little luck trying to figure this out, any help would be much appreciated. Thanks.

like image 806
jjNford Avatar asked Mar 24 '26 11:03

jjNford


1 Answers

If you want to load an already known class from another .apk currently installed on your device you can take the following approach (assuming your class has a default constructor). Also please remember that you must know the package name of the other .apk file and the other .apk file's package name must be different from your applications package name.

private Object loadClass(String packageName, String className){
    Object plugin = null;
    try {
        PackageManager packageManager = getPackageManager();
        ApplicationInfo appInfo = packageManager.getApplicationInfo(packageName, 0);
        DexFile df = new DexFile(appInfo.sourceDir);
        ClassLoader cl = getClassLoader();
        Class classToInvestigate = df.loadClass(className, cl);
        plugin = classToInvestigate.newInstance();


    } catch (Exception e) {
        System.out.println("EXCEPTION");
    }
    finally{
        return plugin;
    }
}
like image 166
Samik Bandyopadhyay Avatar answered Mar 26 '26 23:03

Samik Bandyopadhyay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!