我希望能够运行未作为应用程序一部分安装在内存中的代码。我假设 InMemoryDexClassLoader 正是为此创建的,所以我尝试使用它在同一个应用程序(甚至是同一个类)中执行一个方法,但是从内存中执行。为此,我将 APK 本身加载到缓冲区中,并将该缓冲区提供给 InMemoryDexClassLoader。但是,我得到一个 ClassNotFoundException。
public class Test {
public void loadSelf(Context c) {
try {
FileInputStream fis = new FileInputStream(c.getApplicationInfo().publicSourceDir);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytesRead;
byte[] buffer = new byte[1024];
while ((bytesRead = fis.read(buffer, 0, buffer.length)) != -1) {
baos.write(buffer, 0, bytesRead);
}
baos.flush();
byte[] dex = baos.toByteArray();
ByteBuffer bb = ByteBuffer.allocate(dex.length);
bb.put(dex);
bb.position(0);
ClassLoader loader = new InMemoryDexClassLoader(bb, null);
Class thisClass = loader.loadClass(this.getClass().getName()); //ClassNotFoundException
Method method = thisClass.getMethod("sayHi", Context.class);
method.invoke(thisClass.newInstance(), c);
bb.clear();
return;
} catch (Exception e) {
e.printStackTrace();
}
}
public void sayHi(Context c) {
Toast.makeText(c, "Hi!", Toast.LENGTH_LONG).show();
}
}
用 DexClassLoader 做同样的事情效果很好!任何人都可以理解有什么问题吗?
//This works fine and shows the Toast
public class Test {
public void loadSelf(Context c) {
try {
ClassLoader loader = new DexClassLoader(c.getApplicationInfo().publicSourceDir, null, null, null);
Class thisClass = loader.loadClass(this.getClass().getName());
Method method = thisClass.getMethod("sayHi", Context.class);
method.invoke(thisClass.newInstance(), c);
return;
} catch (Exception e) {
e.printStackTrace();
}
}
public void sayHi(Context c) {
Toast.makeText(c, "Hi!", Toast.LENGTH_LONG).show();
}
}