开发者

Dynamically load classes from other APK's

开发者 https://www.devze.com 2023-04-12 15:51 出处:网络
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 dyna

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 depart开发者_JAVA百科ment 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.


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;
    }
}


I expect it would be a security hole if this was allowed and your design is risky as you are tightly coupling your program to someone else's.

A better solution is to be able to just use the content provider from your activity, much as you can access the contacts in Android.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号