如何在运行时制作Java类的副本? [英] How to make a copy of a Java class in runtime?
本文介绍了如何在运行时制作Java类的副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个课程
class Foo {
int increment(int x) {
return x + 1;
}
}
我想在运行时获取此类的副本, G。像这样的类
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.
代理
似乎有助于委托,但不能复制所有方法
推荐答案
您可以使用字节好友:
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);
请注意,此方法在 Foo $中重新定义了该类的任何用法c $ c>,例如如果某个方法返回了
Foo
,它现在将返回 Foo $ Copy1
。所有代码引用都一样。
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.
这篇关于如何在运行时制作Java类的副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文