Dexmaker is new and designed just for this. Here's part of the example from the project website:
DexMaker dexMaker = new DexMaker();
// Generate a HelloWorld class.
TypeId<?> helloWorld = TypeId.get("LHelloWorld;");
dexMaker.declare(helloWorld, "HelloWorld.generated", Modifier.PUBLIC, TypeId.OBJECT);
generateHelloMethod(dexMaker, helloWorld);
// 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 our newly-generated code in-process.
helloWorldClass.getMethod("hello").invoke(null);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…