leventov leventov - 5 months ago 37
Java Question

How to make a copy of a Java class in runtime?

I have a class

class Foo {
int increment(int x) {
return x + 1;

I want to obtain a copy of this class in runtime, e. g. a class like

class Foo$Copy1 {
int increment(int x) {
return x + 1;

Which has all the same methods, but a different name.

seem to help with delegating, but not copying the methods with all their bodies.


You can use Byte Buddy for this:

Class<?> type = new ByteBuddy()

Method method = type.getDeclaredMethod("increment", int.class);
int result = (Integer) method.invoke(type.newInstance(), 1);

Note that this approach redefines any uses of the class within Foo, e.g. if a method returned Foo, it would now return Foo$Copy1. Same goes for all code-references.