Perform runtime Dalvik bytecode generation with DexMaker
mainDexmaker provides a low-level API for generating Dalvik .dex files instruction-by-instruction. This mirrors the Dalvik bytecode specification.
To generate and load code at runtime:
- Instantiate
DexMaker. - Use
TypeIdto define types (e.g.,TypeId.get("LHelloWorld;")). - Use
dexMaker.declare(...)to declare classes and methods. - Use the returned
Codeobject to append instructions (e.g.,loadConstant,op,invokeStatic,returnVoid). - Call
dexMaker.generateAndLoad(...)to create the dex file and load it into aClassLoader.
DexMaker dexMaker = new DexMaker();
// Generate a class
TypeId<?> helloWorld = TypeId.get("LHelloWorld;");
dexMaker.declare(helloWorld, "HelloWorld.generated", Modifier.PUBLIC, TypeId.OBJECT);
// Generate a method and append instructions
MethodId hello = helloWorld.getMethod(TypeId.VOID, "hello");
Code code = dexMaker.declare(hello, Modifier.STATIC | Modifier.PUBLIC);
Local<Integer> a = code.newLocal(TypeId.INT);
code.loadConstant(a, 0xabcd);
// ... more instructions ...
code.returnVoid();
// Create the dex file and load it
File outputDir = new File(".");
ClassLoader loader = dexMaker.generateAndLoad(HelloWorldMaker.class.getClassLoader(), outputDir, outputDir);
Class<?> helloWorldClass = loader.loadClass("HelloWorld");
// Execute
helloWorldClass.getMethod("hello").invoke(null);