title: What is the best way to calculate a checksum for a Java class?
body: <p>I have an application where I am generating a "target file" based on a Java "source" class. I want to regenerate the target when the source changes. I have decided the best way to do this would be to get a byte[] of the class contents and calculate a checksum on the byte[].</p>
  
  <p>I am looking for the best way to get the byte[] for a class. This byte[] would be equivalent to the contents of the compiled .class file. Using ObjectOutputStream does <em>not</em> work. The code below generates a byte[] that is much smaller than the byte contents of the class file.</p>
  
  <pre><code>// Incorrect function to calculate the byte[] contents of a Java class
  public static final byte[] getClassContents(Class&lt;?&gt; myClass) throws IOException {
      ByteArrayOutputStream buffer = new ByteArrayOutputStream();
      try( ObjectOutputStream stream = new ObjectOutputStream(buffer) ) {
          stream.writeObject(myClass);
      }
      // This byte array is much smaller than the contents of the *.class file!!!
      byte[] contents = buffer.toByteArray();
      return contents;
  }
  </code></pre>
  
  <p>Is there a way to get the byte[] with the identical contents of the *.class file?  Calculating the checksum is the easy part, the hard part is obtaining the byte[] contents used to calculate an MD5 or CRC32 checksum.</p>