title: Avro: SpecificDatumReader/Writer vs ReflectDatumReader/Writer
body: <p>I have a <code>byte[]</code> representation of Avro payload and the schema which is used to encode/decode this payload. There are a few ways to convert this payload to a SpecificRecord, using ReflectDatumReader/Writer and SpecificDatumReader/Writer. </p>
  
  <p>We get an error when we decode using SpecificDatumReader and try to encode a SpecificRecord returned using ReflectDatumReader. </p>
  
  <p>Below is the sample code. Using SpecificDatumReader to get a SpecificRecord (Testing) then using ReflectDatumWriter to attempt to encode it into a byte[], which fails. Finally using a SpecificDatumReader to re-decode it.</p>
  
  <pre><code>DatumWriter&lt;Testing&gt; refWriter = new ReflectDatumWriter&lt;&gt;(expectedSchema);
  DatumReader&lt;Testing&gt; specReader = new SpecificDatumReader&lt;&gt;(expectedSchema);
  
  // Use SpecificDatumReader to decode to a SpecificRecord
  Testing r1 = specReader.read(null, DecoderFactory.get().binaryDecoder(expectedBytePayload, null));
  
  // Use ReflectDatumWriter to write SpecificRecord encode as byte[].
  // Note: this step fails
  ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  refWriter.write(r1, EncoderFactory.get().binaryEncoder(outStream, null));
  
  // Use SpecificDatumReader to decode to a SpecificRecord
  Testing r2 = specReader.read(null, DecoderFactory.get().binaryDecoder(outStream.toByteArray(), null));
  </code></pre>
  
  <p>Error Message:</p>
  
  <pre><code>java.io.EOFException
      at org.apache.avro.io.BinaryDecoder.ensureBounds(BinaryDecoder.java:473)
      at org.apache.avro.io.BinaryDecoder.readDouble(BinaryDecoder.java:243)
      at org.apache.avro.io.ResolvingDecoder.readDouble(ResolvingDecoder.java:190)
      at org.apache.avro.generic.GenericDatumReader.readWithoutConversion(GenericDatumReader.java:185)
      at org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:152)
      at org.apache.avro.generic.GenericDatumReader.readField(GenericDatumReader.java:240)
      at org.apache.avro.generic.GenericDatumReader.readRecord(GenericDatumReader.java:230)
      at org.apache.avro.generic.GenericDatumReader.readWithoutConversion(GenericDatumReader.java:174)
      at org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:152)
      at org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:144)
  </code></pre>
  
  <ol>
  <li>Why aren't they interchangeable?  </li>
  <li>When do we use one over another?</li>
  </ol>