Reputation: 5270
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.
Upvotes: 3
Views: 3764
Reputation: 1475
Updated version of Samik Bandyopadhyay answer
private Object loadClass(String packageName, String className){
Object plugin = null;
try {
PackageManager packageManager = getPackageManager();
ApplicationInfo appInfo = packageManager.getApplicationInfo(packageName, 0);
ClassLoader cl = getClassLoader();
PathClassLoader pathClassLoader = new PathClassLoader(appInfo.sourceDir, cl);
Class classToInvestigate = pathClassLoader.loadClass(className);
plugin = classToInvestigate.newInstance();
} catch (Exception e) {
System.out.println("EXCEPTION");
}
finally{
return plugin;
}
}
Upvotes: 0
Reputation: 868
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;
}
}
Upvotes: 11
Reputation: 41858
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.
Upvotes: 0