dynamically load class into memory
DexClassLoader is great but works only by loading the compiled class as dex/jar file from the internal/external storage.
How can I load class directly into memory, without writing anything to the card first?
I am aware of the Java-Runtime-Compiler (compiles String to Class on-the-fly) from Peter Lawrey, which would be perfect, but it does not work in android.
The general principles for writing Java class loaders apply here as well, so basically what you need to do is write a class loader that can produce a Class
instance, for example by invoking defineClass()
. Of course this involves creating a valid array of dex bytecode. I have not done so yet, and besides very special occasions I would refraim from attempting to do so anyway. If you follow this road, remember to only use classloader features that have been present in Java 5 and 6.
As Thomas stated, you can reflectively invoke the protected defineClass()
method of the ClassLoader into which you would like to load your class.
Here's an example of how this could be achieved:
public static Class<?> loadClass(byte[] code, ClassLoader loadInto) throws InvocationTargetException
{
try {
Method m = ClassLoader.class.getDeclaredMethod("defineClass", byte[].class, int.class, int.class);
m.setAccessible(true); // Make sure we can invoke the method
return (Class<?>) m.invoke(loadInto, code, 0, code.length);
}
// An exception should only be thrown if the bytecode is invalid
// or a class with the same name is already loaded
catch (NoSuchMethodException e) { throw new RuntimeException(e); }
catch (IllegalAccessException e){ throw new RuntimeException(e); }
}
Although, what I'm getting the feeling that you're referring to is runtime compilation of a String containing valid Java into bytecode, based on the link you included. Though I do not know of any way of doing this, I would recommend you take a look at this: https://github.com/linkedin/dexmaker
链接地址: http://www.djcxy.com/p/62554.html上一篇: 用于优化dex(odex)文件的Android类加载器
下一篇: 将类动态加载到内存中