How to make a copy of the Java class at runtime?

I have a class

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

I want to get a copy of this class at runtime, e. class like

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

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

Proxyseems to help in the matter of delegation, but not in copying methods with all their bodies.

+4
source share
3 answers

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 overrides any class application in Foo, for example. if the method returned Foo, it will now return Foo$Copy1. The same goes for all code links.

+8
source

, Unsafe , -.

- Foo.class.getClassLoader().getResourceAsStream() - .

sun.misc.Unsafe.defineClass(String name, byte[] code, int off, int len, ClassLoader classLoader, ProtectionDomain protectionDomain), loader , Foo, .

, - .

0

Source: https://habr.com/ru/post/1661766/


All Articles