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.
Proxy
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.
Foo
Foo$Copy1
@leventov, ? https://gist.github.com/serkan-ozal/8737583841b4b12e3a42d39d4af051ae
, Unsafe , -.
- Foo.class.getClassLoader().getResourceAsStream() - .
Foo.class.getClassLoader().getResourceAsStream()
sun.misc.Unsafe.defineClass(String name, byte[] code, int off, int len, ClassLoader classLoader, ProtectionDomain protectionDomain), loader , Foo, .
sun.misc.Unsafe.defineClass(String name, byte[] code, int off, int len, ClassLoader classLoader, ProtectionDomain protectionDomain)
, - .
Source: https://habr.com/ru/post/1661766/More articles:Vue-wrap HTML5 element - javascriptMagento PayPal Payment Pro не отправляет письмо с подтверждением - phpNet Bash Replacement Capture Group - bashFunction inside onload function undefined? - javascriptNginx returns 404 error for some angularJS urls for a while - angularjsValidation ticks error including andalso macro in ATS - atsLimit a generic type to one of several types - rustIs it possible to serialize an ArrayList of objects containing a BufferedImage as one of the variables of a private instance of an object in java? - javaThe enzyme does not find the component with the requisite - reactjsПостепенно прокручивайте мышь до мышки - javascriptAll Articles