Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 586
leventov Avatar asked Nov 23 '16 21:11

leventov


People also ask

How to make a copy of an object Java?

In Java, there is no operator to create a copy of an object. Unlike C++, in Java, if we use the assignment operator then it will create a copy of the reference variable and not the object.

What is runtime class Java?

In Java, the Runtime class is used to interact with Every Java application that has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime() method.


1 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 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.

like image 130
Rafael Winterhalter Avatar answered Sep 19 '22 11:09

Rafael Winterhalter