Firstly, I saw Download Java bytecode at runtime , and it was useful since I came to me in the same place where I was stuck at the moment.
I am trying to load a class from an array of bytes to avoid storing the file on disk. For testing purposes, in this example, I just read the .class file into an array of bytes, so obviously the file is still stored on disk, but it's just to see if the code can work.
I take this byte array and then use my own ClassLoader with the loadClass method to load the class, but it does not work.
byte[] bytearray = null;
try{
RandomAccessFile f = new RandomAccessFile("/sdcard/ClassToGet.dex", "r");
bytearray = new byte[(int) f.length()];
f.read(bytearray);
MyClassLoader classloader = new MyClassLoader();
classloader.setBuffer(bytearray);
classloader.loadClass("com.pack.ClassIWant");
}
Here is the implementation of ClassLoader:
public class MyClassLoader extends DexClassLoader {
private byte[] buffer;
@Override
public Class findClass(String className){
byte[] b = getBuffer();
return this.defineClass(className, b, 0, b.length);
}
public void setBuffer(byte[] b){
buffer = b;
}
public byte[] getBuffer(){
return buffer;
}
And the error I get is this:
java.lang.UnsupportedOperationException:
java.lang.VMClassLoader.defineClass( )
.class, .dex,.apk,.jar .. , " " , . . .