I am sending Pencil object form Kafka producer to Kafka as message and it sending those to consumer and its picking those message at line 27 in https://github.com/jitendraVishnoi/kafka/blob/master/src/main/java/CustomExecutor.java its able to print those Pencil messages. If there is method say void sellPencil(Pencil pencil), I need to just cast it like (Pencil) bean.value() and pass it. Everything works fine.
I understand I am missing some basic concepts. I got it how its not giving any error at compile time but if its not generic related how its working, Could you please help me understand.
Appreciate all your support.
The fact that it works makes me even more wary of Apache Kafka.
Each bean that you iterate over should be a Consumer<String, KafkaRecord>, meaning that bean.value() is a KafkaRecord, and therefore can't be a Pencil.
You are likely correct that it works because of type erasure, but that also means that Apache Kafka doesn't take type safety seriously. Its use of generics only serves to give a false sense of security.
I added below method(GIT code also updated) and pencilRecords.forEach(bean -> playWithRecord(bean.value()));
I tried with private void playWithRecord(KafkaRecord record) but its failing in runtime while receiving message -
Looks to me only reason why Consumer<String, KafkaRecord> pencilConsumer = getPencilConsumer(); is successful if type is erased as any futher line which trying to consider record as KafkaRecord is ClassCastException.
Let me know about your thoughts or if there is way to check what is code at runtime.
Yes, it works because of type erasure and because Kafka allows you to set a deserializer without connecting the type of the deserializer to the type of the records you get from the consumer. Bad design.
I would just continue with whatever you are doing. Just stop casting object references. If you need references of type Pencil, create a Consumer<String, Pencil> and not a Consumer<String, KafkaRecord>. If you don't, and your Pencil really does represent a Kafka record, then why not let it extend KafkaRecord.
Just stop casting object references. If you need references of type Pencil, create a Consumer<String, Pencil> and not a Consumer<String, KafkaRecord>.
Actually its like we are getting different type of objects and that's why wanted to keep common part in some super class. Its like everyone will override their playWithRecord in thier own way and we dont have write duplicate code.
If you don't, and your Pencil really does represent a Kafka record, then why not let it extend KafkaRecord.
Yes Pencil is a Kafka record and it was accedently missed but the problem is its working fine.
If I have to ask someone to update the code I am not sure about the logic I would give as its working now and after the change it will keep working.