2014年3月7日 星期五

ClassLoader in Android

PathClassLoader:
Load class from Android system. So those classes have to be registered in system. They may be a installable APK. And the class(dex files) would storage in /data/dalvik-cache


        String packageName = "com.android.calculator2";
        String className = "com.android.calculator.sample.class";

        String apkSourcePath;
        apkSourcePath =getPackageManager().getApplicationInfo(packageName, 0).sourceDir;

         PathClassLoader pathClassLoader = new dalvik.system.PathClassLoader(apkSourcePath,
                    ClassLoader.getSystemClassLoader());
          Class clazz = pathClassLoader.loadClass(className);
          Method[] methods = clazz.getMethods();
          for (Method m : methods) {
                Log.i("","method name:" + m.getName());
           }


DexClassLoader:
Load class from jar, apk file. Those file is stored in accessible storage, such as internal storage or sd card. When class loader loads jar file, it will generate dex file. Then load class from dex file.

Example:
           Put  com.android.calculator.jar in /data/data/MY_APP_PACKAGE/files    

            File jarFile = new File(getFilesDir().getAbsoluteFile() + File.separator
                    + "com.android.calculator.jar");
            final File optimizedDexOutputPath =getDir("outdex", Context.MODE_PRIVATE);
            DexClassLoader dexClassLoader = new DexClassLoader(jarFile.getAbsolutePath(),
                    optimizedDexOutputPath.getAbsolutePath(),
                    null,
                    ClassLoader.getSystemClassLoader());
            Class clazz = dexClassLoader.loadClass("com.android.calculator.sample.class");
            Method[] methods = clazz.getMethods();
            for (Method m : methods) {
                Log.i("","method name:" + m.getName());
            }
            Constructor constructor = clazz.getConstructor(Context.class);
            Object instance = constructor.newInstance();

沒有留言:

張貼留言