leventov leventov - 11 days ago 6
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.

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

Answer

You can use Byte Buddy for this:

Class<?> type = new ByteBuddy()
  .redefine(Foo.class)
  .name("Foo$Copy1")
  .make()
  .load(Foo.class.getClassLoader())
  .getLoaded();

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.

Comments