Search code examples
javaandroidclassloader

Android: How to dynamically load classes from a JAR file?


I'm trying to dynamically load a class at runtime on the Android platform. The class is contained within a separate library JAR file, but packaged with the APK (as per the new library mechanism in the SDK). When using Class.forname method, I received a class not found exception. I've seen some discussion around the DexClassLoader method, but I can't find a good example of how it's used (and whether it's the best way to go about it - it seems a lot more complicated than the forname approach!).

I would be very grateful if someone could provide an example snippet of code of how to go about this.

Many thanks for your help.


Solution

  • Here's an example to dynamically load the DevicePolicyManager class.

    Class myClass =                                                                        
      ClassLoader.getSystemClassLoader().loadClass("android.app.admin.DevicePolicyManager")
    
    Object DPMInstance = myClass.newInstance();                                            
    
    Method myMethod = myClass.getMethod("setPasswordQuality",                              
                                        new Class[] { ComponentName.class,                 
                                                      int.class });                        
    myMethod.invoke(DPMInstance,                                                           
                    new Object[] { myComponentName,                                        
                                   PASSWORD_QUALITY_NUMERIC }); 
    

    This is useful so you can choose to only load a class when the device is running a high enough SDK version.