The Android program can dynamically generate objects at run time, invoking methods through the dynamic class loading method.
It can be loaded dynamically in Android, but it is not as easy to dynamically load jars as in Java.
Cause: The Android virtual machine (Dalvik VM) is a byte code that does not recognize the Java-typed jar and needs to be optimized for conversion to Dalvik byte code by using the DX tool.
1. First generate the called Dex file:
Package com.dynamic;
Public interface Idynamic {
Public String HelloWorld ();
}
Package com.dynamic;
public class Idynamictest implements idynamic{
Public String HelloWorld ()
{
Return "Hello World";
}
}
Construct the HelloWorld function, package the code export into a 1.jar file, call the Android-powered DX tool, and compile the 1.jar file into a Test.jar containing the Dex file.
2. In Android code, call the HelloWorld function in Test.jar.
public void OnClick (View v) {
Button1.settext ("Lauclass (M1)");
Final file Dexpathfile = new file ("/data/app/test.jar"); Specify the jar file location
Dexclassloader ClassLoader = new Dexclassloader (Dexpathfile.getabsolutepath (), "/data/app/", NULL, getClassLoader ()); Generate ClassLoader
try{
Class Libprovideclass = Classloader.loadclass ("Com.dynamic.IDynamicTest"); Using ClassLoader to load the class in
if (libprovideclass==null)
{
return;
}
Object obj=libprovideclass.newinstance (); Generating an instance object using the resulting class
Method MethodInstance = Libprovideclass.getmethod ("HelloWorld", null); Gets the object's method object
if (methodinstance==null)
{
Finish ();
}
Toast.maketext (Secondclass.this, (String) Methodinstance.invoke (obj,null), Toast.length_short). Show (); Trigger HelloWorld method
} catch (Exception Exception)
{
Exception.printstacktrace ();
}
}
Related URL:
http://my.oschina.net/Jerryking/blog/111575
Http://www.cnblogs.com/over140/archive/2011/11/23/2259367.html
Android Dynamic class Loading