我目前使用 Javaassist 为类生成代理:
ProxyFactory f = new ProxyFactory();
f.setSuperclass(JFrame.class); // Just an example.
// I would like to create a proxy for JFrame to
// fill with method implementations...
f.setHandler(handler); // ... in an own handler
Class<?> proxyClazz = f.createClass();
我的问题是:JFrame 构造函数也被调用。说得通。但我不想要这个。我想生成一个空类作为代理,它与其他普通 JFrame 兼容分配。
有办法做到这一点吗?感谢您提供的所有想法和想法。
最佳答案
- 序列化
您可以以序列化形式创建表示所需类的字节数组,并使用ObjectInputStream.readObject
。
这是可能的,但很难准备正确的数据。
NativeConstructorAccessorImpl
这就是 spy
方法在 mockito
中的实现方式。
Unsafe.allocateInstance
因此,您准备代理类并实例化其中一种方法(或其他方式)。
PS:看看objenesis
图书馆。
关于没有构造函数的 Javassist 代理类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47153148/