4
클래스를 바이트 배열로로드하려고하므로 네트워크를 통해 전송하고 Reflection을 통해 원격으로 실행할 수 있습니다. 이 클래스 (이 경우 버블)는 동일한 패키지에 있습니다. 것은 getResourceAsStream (classpath) 메소드를 사용하여 리소스를 가져올 수 없다는 것입니다. .getResourceAsStream (클래스 경로)은 항상 null을 반환합니다. Java 프로젝트에서이 코드를 테스트하고 올바르게 작동했습니다. 문제는 리소스 경로라고 생각합니다. 안드로이드는 .class 파일을로드합니까?Android에서 ClassLoader를 사용하여 클래스를 바이트 배열로 동적으로로드하십시오.
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;
}