Java reflection: How do I override or generate methods at runtime?

You can use something like cglib for generating code on-the-fly


In java6 has been added the possibility to transform any already loaded class. Take a look at the changes in the java.lang.instrument package


For interfaces there is java.lang.reflect.Proxy.

For classes you'll either need a third-party library or write a fair bit of code. Generally dynamically creating classes in this way is to create mocks for testing.

There is also the instrumentation API that allows modification of classes. You can also modify classes with a custom class loader or just the class files on disk.