Android Dynamic class Loading

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.