-2

I'm writing a tool that need to get an instance of java.io.Serializable from a byte array.
The difficulty is that the "real" class is not (and cannot be...) on the classpath (I will not explain why here..).
The code below fails on is.readObject() with a ClassNotFoundException because the implementation class is not on the classpath
Q:
Is is possible to achieve this? by reflection? by using Unsafe? by using a sub class of ClassLoader? or...?

byte[] data = ...
try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));) {
   Object o = ois.readObject();
   Serializable s = (Serializable)o;
}
user207421
  • 305,947
  • 44
  • 307
  • 483
titou10
  • 2,814
  • 1
  • 19
  • 42
  • 1
    *Is is possible to achieve this?* Not without the implementation. Yes you could write a `ClassLoader` to load the `class`. But then you're back to needing the class. – Elliott Frisch Nov 02 '16 at 00:33
  • Ditto what Eliott said. Java serialization sends the data of a class only, not the class itself (not the methods or the definitions of what the data means). Without the class, you are sunk. – markspace Nov 02 '16 at 00:40
  • I would love to know why the downvotes...it is "bad" to ask this kind of question? or induced othere users into error? or give a false anser? I don't think so.. – titou10 Nov 02 '16 at 12:20

1 Answers1

1

Is iis possible to achieve this?

No.

by reflection?

No.

by using Unsafe?

No.

by using a sub class of ClassLoader?

Yes but the class loader still has to get the class from somewhere. The RMI codebase feature is a good example.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • I'm working with JEE and the JMS API. In JMS there is a "ObjectMessage" class (http://docs.oracle.com/javaee/7/api/javax/jms/ObjectMessage.html ) that can encapsulate a "serializable" object. You can get this serializable with the getObject() nethod. This method works even if the implementation class is not on the classpath. So i guess I need to decompile an implementation of this API to examine how they do it – titou10 Nov 02 '16 at 12:23