Android的:如何动态地从一个JAR文件中加载的类? [英] Android: How to dynamically load classes from a JAR file?

查看:157
本文介绍了Android的:如何动态地从一个JAR文件中加载的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在运行在Android平台上动态加载的类。类被包含在一个独立的库JAR文件,但是打包带的APK(按SDK中的新的库机构)。当使用Class.forName方法,我收到了找不到类异常。我看到周围的DexClassLoader方法进行一些讨论,但我无法找到如何使用它一个很好的例子(无论是去了解它的最好方式 - 这似乎是一个很多比中的forName方法更复杂!)<。 / P>

我会很感激,如果有人可以提供$ C $的如何去本C为例片段。

非常感谢您的帮助。

解决方案

下面是一个例子,动态的加载 DevicePolicyManager 类。

  MyClass类=
  ClassLoader.getSystemClassLoader()的loadClass(android.app.admin.DevicePolicyManager)

对象DPMInstance = myClass.newInstance();

方法myMethod的= myClass.getMethod(setPasswordQuality
                                    新等级[] {ComponentName.class,
                                                  int.class});
myMethod.invoke(DPMInstance,
                新对象[] {m​​yComponentName,
                               PASSWORD_QUALITY_NUMERIC});
 

这是很有用的,所以你可以选择只在设备运行的足够高的SDK版本加载类。

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.

解决方案

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.

这篇关于Android的:如何动态地从一个JAR文件中加载的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆