如何通过电线发送课程 [英] How to send a Class over the wire
问题描述
我有以下问题:我想通过线路发送一个类型(java.lang.Class)并在另一侧'定义'该类。
I have the following problem: I want to send a type (java.lang.Class) over the wire and 'define' the class on the other side.
我试过这样:
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
所以显然我需要发送类的原始字节码并做一个
so obviously I need to send the raw bytecode of the class and do a
ClassLoader.defineClass(bytes, ..
但不幸的是我没有看到如何检索已加载类的字节码。
我正在搜索类似的内容:
but unfortunately I fail to see how I can retrieve the bytcode of a loaded class. I'm searching for something like:
byte[] byteCode = MyClass.class.toByteArray();
这是否可以使用标准JDK或者是否有任何小型lib可以做到这一点?
Is this even possible with standard JDK or is there any small lib out there that can do that?
推荐答案
我不喜欢我认为你想要的东西是完全通用的。从字节码中定义一个类的行为是不可逆的。但你应该做的是直接读取字节码文件(假设它是 URLClassLoader
):
I don't think what you want is possible in full generality. The act of defining a class from its bytecode is not reversible. What you should be able to do, however, is to directly read the bytecode file (assuming that it's an URLClassLoader
):
MyClass.class.getResourceAsStream("Myclass.class")
或者,你可以通过HTTP访问类文件,并在接收方直接使用 URLClassLoader
。
Alternatively, you could just make the class files accessible via HTTP and directly use an URLClassLoader
on the receiving side.
这篇关于如何通过电线发送课程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!