Sending Java object of unknown class

for a long time, but could not find the answer to this question:

I have a server and I have a client. The server should receive the object through ObjectInputStreamand ObjectOutputStream. This already works for anyone classknown on the server. Now I want to send Objectfrom classwhich the server does not know. He knows the interface of this class. And this clearly fails ...

How can i avoid ClassNotFoundException? I thought interfaces were a solution. I just want to access the functions that I know by the interface, but Java still wants to have a class.

Thank.

+2
source share
3

. , . .

+3

JVM , JVM . , , , , , .. HashMap. , , :

MySecretClass o = new MySecretClass ();
o.setFoo ("Hello, World!");
o.setBar (123);
send (o);

:

Map o = new HashMap ();
o.put ("foo", "Hello, World!");
o.put ("bar", 123);
send (o);
0

- , , .

- , , . - , , - . - Externalizable Classloader.defineClass JVM, ( ). , , , ..

If you need to call interface-specific methods directly on the object transferred from the client, make the proxy interface implement its interface and use the dynamic proxy server template for the proxy object (java.lang.reflect.Proxy / InvocationHandler) to transfer calls to the proxy an object of a previously unknown class.

It is rather complicated, but can be done so, I think.

0
source

Source: https://habr.com/ru/post/1742909/


All Articles