Class loader in Android Dexclassloader

Source: Internet
Author: User

http://blog.csdn.net/com360/article/details/14125683

Java, there is a concept called "ClassLoader" (ClassLoader), it is the role of dynamic loading class files.    There is a ClassLoader class in the standard Java SDK that allows you to load the desired class file, and each ClassLoader object must have a path to the class file when it is initialized. Some people may ask, when writing a program is not the Import keyword can refer to the established class?Why do you use this classloader?       The reason for this is that a class referenced with the import keyword must conform to the following two conditional class files that must be local, and when the program runs with a secondary class, the class loader automatically loads the class, and the programmer does not need to pay attention to this process.    Compile must have this class file, otherwise the compilation does not pass. What if you want the program to be dynamically invoked when it is running? The import display does not meet the above two requirements.    This is where ClassLoader comes in handy. Please refer to this link HTTP for the loading mechanism of Java ClassLoader://www.iteye.com/topic/83978, it's best to search the Internet on your own. http//www.artima.com/insidejvm/ed2/"Inside the Java virtural machine"for Android applications, it's essentially Java development, using a standard Java compiler to compile a class file, and, unlike normal Java development, to repackage class files into Dex-type files. This repackaging optimizes various function tables, variable tables, and so on within the class file, resulting in a Dex file. The Dex file is a class file optimized by the Android packaging tool, so loading a special class file requires a special ClassLoader, so the Dexclassloader class is available in Android. Class loader Dexclassloader class structure inheritance relationship: AclassLoader that loads classes from. jar and. apk files containing a classes.dex entry. This can is used to execute code not installed asPart of the application. thisclassLoader requires an application-Private, writable directory to cache optimized classes. Use Context.getdir (String,int) to create such a directory:file dexoutputdir= Context.getdir ("Dex",0); Do not caches optimized classes on external storage. External storage does not provide access controls necessary to protect your application fromcode injection attacks. Translator: This classloader is used to load classes.dex files from within. jar and. apk type files.    This can be used to execute non-installed program code and run as part of the program. This load class requires a program-private, writable file directory to store the optimized classes file. by Contexct.getdir (String,int) to create this directory: File dexoutputdir= Context.getdir ("Dex",0); Do not store optimized classes files on external storage devices, preventing code injection attacks. This class has only one constructor: PublicDexclassloader (String Dexpath, String optimizeddirectory, String LibraryPath, ClassLoader parent) AddedinchAPI level3creates a dexclassloader that finds interpreted and native code. Interpreted classes is foundinchASetof DEX files containedinchJar or APK files. Create a dexclassloader to find the specified class and local code (c/c++code). Used to interpret the class file executed in the Dex file. The delimiter for the path is obtained by using the properties of the system Path.separator:. String Separeater= System.getproperty ("Path.separtor"); Parametersdexpath the path of the APK or jar file that needs to be loaded. Contains multiple paths with File.pathseparator interval, on Android default is":"optimizeddirectory optimized dex file storage directory, cannot be used in Nulllibrarypath target class CA list of/c++ libraries, each separated by a file.pathseparator interval; Can thinkNULLthe parent loader of the class loader, typically using the loader class loader of the current execution class, dexclassloader the use of this class basically: Get the directory of the installation of the specified APK by Pacagemangager, Dex's Unzip directory , C/c++Library Directory Create a Dexclassloader instance load the specified class and then use reflection to call this class below is the Code section, code reference from the "Android Kernel Anatomy" (author Ke New Year, the book is good, recommended reading): [HTML] View Plaincopy @SuppressLint ("Newapi")Private voidUsedexclassloader () {//Create an intent to find the specified apkIntent Intent =NewIntent ("Com.suchangli.android.plugin",NULL); //Get Package ManagerPackagemanager pm =Getpackagemanager (); List<ResolveInfo> resolveinfoes = pm.queryintentactivities (Intent,0); //get the information for the specified activityActivityinfo actinfo = resolveinfoes.Get(0). Activityinfo; //get the package nameString Pacagename =Actinfo.packagename; //get the directory of the APK or the directory of the JarString Apkpath =ActInfo.applicationInfo.sourceDir; //Dex Unzip the directory, note that this directory with the host program, Android only allows programs to read and write their own//files under the directoryString Dexoutputdir =getapplicationinfo (). DataDir; //directory of native codeString LibPath =ActInfo.applicationInfo.nativeLibraryDir; //Create the ClassLoader and load Dex into the virtual machineDexclassloader Calssloader =NewDexclassloader (Apkpath, Dexoutputdir, LibPath, This. GetClass (). getClassLoader ()); //methods for invoking classes within a plug-in package with reflection                  Try{Class<?> clazz = Calssloader.loadclass (pacagename+". Plugin1"); Object obj=clazz.newinstance (); class[] param=Newclass[2]; param[0] =Integer.type; param[1] =Integer.type; Method Method= Clazz.getmethod ("function1", param); Integer ret= (Integer) method.invoke (obj,1, A); LOG.I ("Host","return result is"+ret); } Catch(ClassNotFoundException e) {e.printstacktrace (); } Catch(instantiationexception e) {e.printstacktrace (); } Catch(illegalaccessexception e) {e.printstacktrace (); } Catch(nosuchmethodexception e) {e.printstacktrace (); } Catch(IllegalArgumentException e) {e.printstacktrace (); } Catch(InvocationTargetException e) {e.printstacktrace ();            }} A class in plugin1.apk: [HTML] View plaincopy package com.suchangli.plugin1;  Public classPlugin1 { Public intFunction1 (intAintb) {                            returnA +b; }} The result of the log output: Note To add the following action to an activity in the manifest file in Plugin1, the action must be the host and plugin conventions. Source code: You can access the code in another apk with the above code, a more troublesome place is to use reflection to call the method, there is no reflection can also invoke method mode? Of course there is, through the interface. 

Class loader in Android Dexclassloader

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.