Dynamically load a class as an array of bytes using ClassLoader in Android

I am trying to load a class as a byte array so that I can send it over the network and execute it remotely via Reflection. This class (Bubble in this case) is in one package. The thing is, I cannot get the resource using the getResourceAsStream (classpath) method. .getResourceAsStream (classpath) always returns null. I tested this code in a Java project and worked correctly. I think the problem is in the resource path, does Android download the .class file?

private void doSomething() {

    Bubble b = new Bubble();

    try {
        //Try to retrieve the class byte array
        byte[] classBytes = getBytes(b.getClass());         
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
    ... 
}

private byte[] getBytes(Class c) throws IOException{

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    byte b[] = new byte[1024];
    String classpath = c.getCanonicalName().replace('.', File.pathSeparatorChar) + ".class";
    //classpath is now, for example, com:myproject:Bubble.class
    InputStream in = c.getClassLoader().getResourceAsStream(classpath);
    int load;
    while((load=in.read(b))>0){
        out.write(b,0,load);
    }
    byte[] _r = out.toByteArray();
    out.close();
    in.close();
    return _r;
}
+4
source share
1 answer

Android dex , zipped (jarred) classes.dex, , .

0

Source: https://habr.com/ru/post/1544934/


All Articles