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

久未见 提交于 2019-12-04 03:58:51

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/7947422/android-how-to-dynamically-load-classes-from-a-jar-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!