0

Had faced an interesting case: There is some "space"(Mq-queue, Kafka-topic, simple folder, whatever). In this space writing Java-Object in serialized form. There is a listener that listens to this space. The question is: How can I, as this listener, get some data from this serialized object, without realization of this class in my listener.

I don't really want to see all the logic of this class. To see object fields is enough(for example as map: someObjectField=>someFieldValue).

Now when I try to deserialize this object, I catch "classNotFoundException". Is there a possibility to avoid that problem, without rewriting all default Java deserialization logic? (maybe some tools already exist?)

SUNIL DHAPPADHULE
  • 2,755
  • 17
  • 32
  • Serialized objects are meant to be deserialized. You're asking how to use a (java) serialized object without deserialization. Sounds like you should be using a different serialization mechanism instead, such as json. – Kayaman May 17 '18 at 12:37
  • 1
    (Hint: https://superuser.com/questions/1107042) – Stephen C May 17 '18 at 13:05
  • @StephenC thanks A LOT! Exactly what I'm looking for. – Hank Hank May 17 '18 at 14:38

1 Answers1

0

I think you didn’t specifies the deserializer. Actually while creating the consumer you need to give the deserializer class in the properties of the consumer along with the boot strap server and other properties. e.g.

public class KafkaConsumerExample {
  ...

  private static Consumer<Long, String> createConsumer() {
     final Properties props = new Properties();
      props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,
                                  BOOTSTRAP_SERVERS);
      props.put(ConsumerConfig.GROUP_ID_CONFIG,
                                  "KafkaExampleConsumer");
      props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
              LongDeserializer.class.getName());
      //depends on your key serialiser if it’s long then you should use long or else what ever data type you use 
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
                  StringDeserializer.class.getName());

      // Create the consumer using props.
      final Consumer<Long, String> consumer =
                                  new KafkaConsumer<>(props);

      // Subscribe to the topic.
      consumer.subscribe(Collections.singletonList(TOPIC));
      return consumer;
  }
  ...
}

If you are using some custom serializer then you will have to create the custom deserializer.

Raman Mishra
  • 2,635
  • 2
  • 15
  • 32