Android 載入其他Apk中的類方法
阿新 • • 發佈:2019-02-13
public void loadApkClass(String apkPath, Context context) {
//app路徑下的資料夾名稱
File dexOutputDir = context.getDir("dex", 0);
//被載入的Class
String className = "com.mz.testapk.TestClass";
DexClassLoader classLoader = new DexClassLoader(apkPath, dexOutputDir.getAbsolutePath(), null, getClassLoader());
try {
Class mLoadClass = classLoader.loadClass(className);
//預設構造方法
Constructor constructor = mLoadClass.getConstructor(new Class[]{});
Object testClass = constructor.newInstance(new Object[]{});
//TestClass 中的getStr方法
Method getStr = mLoadClass.getDeclaredMethod("getStr", null);
getStr.setAccessible(true);
Object money = getStr.invoke(testClass, null);
Toast.makeText(this, money.toString(), Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
// TestClass程式碼
package com.mz.testapk;
public class TestClass {
public String getStr() {
return "TestClassStr";
}
}