I have an abstract class in Java roughly similar to a thread, and another one that schedules my “threads” to actual java threads. What I want to do is create classes that inherit from my “thread” class, override the run() function, and then make them serializable and send them over a network where they can be run elsewhere.
The obvious problem is that the receiver won’t know about the actual class being sent, and even casting that class to its super class won’t help.
What I want to know is, is there a way to serialize anonymous bytecode to be sent across a network? If so, how? Examples much appreciated.
The java serialization serializes objects, i.e. instances of classes. When you serialize object you actually store somehow values of it member fields. The logic of methods is beyond serialization – it is stored in class file.
What you actually want to do is to send class file and instances of the class over network.
The good new is that you can do this. Find appropriate
classfile using ClassLoader.getResoureAsStream(), send it to other side as a sequence of bytes. The other side should obviously be able to receive it and then to callClassLoader.defineClass(String name, byte[] b, int off, int len)Since this moment the class that was known by your sender application will be available at the receiver’s JVM. Now you can use regular serialization mechanism to send instances of this class and everything should work.