我正在尝试将类加载为字节数组,因此我可以通过网络发送它并通过Reflection远程执行它。此类(本例中为Bubble)位于同一个包中。问题是我无法使用getResourceAsStream(classpath)方法获取资源。 .getResourceAsStream(类路径)始终返回null。我已经在Java项目中测试了这段代码并且运行正常。我认为问题是资源路径,Android是否加载.class文件?
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;
}
答案 0 :(得分:0)
Android对类使用dex文件格式,最好的方法是不发送zipped(jarred)classes.dex,它包含你需要的所有类。