我有以下问题:我想通过网络发送一个类型(java.lang.Class)并在另一端“定义”类。
我试过这样:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(MyClass.class);
在接收端:
ByteArrayInputStream bis = new ByteArrayInputStream(request.getBytes());
ObjectInputStream ois = new ObjectInputStream(bis);
Class c = (Class) ois.readObject(); // ClassNotFoundException
所以很明显我需要发送类的原始字节码并做一个
ClassLoader.defineClass(bytes, ..
但不幸的是,我看不到如何检索已加载类的字节码。我正在寻找类似的东西:
byte[] byteCode = MyClass.class.toByteArray();
这甚至可以使用标准 JDK,还是有任何小的库可以做到这一点?