简体   繁体   English

Android:如何从JAR文件动态加载类?

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

I'm trying to dynamically load a class at runtime on the Android platform. 我正在尝试在Android平台上动态加载一个类。 The class is contained within a separate library JAR file, but packaged with the APK (as per the new library mechanism in the SDK). 该类包含在单独的库JAR文件中,但与APK一起打包(根据SDK中的新库机制)。 When using Class.forname method, I received a class not found exception. 使用Class.forname方法时,我收到了一个未找到的类异常。 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!). 我已经看过围绕DexClassLoader方法的一些讨论,但是我找不到一个如何使用它的好例子(以及它是否是最好的方法 - 它似乎比forname方法复杂得多!)。

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. 非常感谢您的帮助。

Here's an example to dynamically load the DevicePolicyManager class. 以下是动态加载DevicePolicyManager类的示例。

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. 这很有用,因此您可以选择仅在设备运行足够高的SDK版本时加载类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM