Inside Java Class Files
by Matt T. Yourst


Listing One
[lti\java\javadump\javadump.java]
package lti.java.javadump;
import java.io.*;
import lti.java.jcf.*;

public class javadump
{
  public static void main(String args[]) throws Exception
  {
    // Open the class file.
    FileInputStream fist = new FileInputStream(args[0]);
    // Create a new specialized input stream to parse the class file
    JcfClassInputStream ist = new JcfClassInputStream(
      new BufferedInputStream(fist, Math.min(fist.available(), 32767)));
    // Read into JcfClassFile object
    JcfClassFile jcf = null;
    jcf = new JcfClassFile(ist);
    fist.close();
    // Perform complete dump
    int flags = 0;
    if ((args.length >= 2) && (args[1].equals("-noconstpool")))
      flags |= DumpClassToHtml.OMIT_CONSTPOOL;
    new DumpClassToHtml(jcf, System.out, flags).dump();
  }
}


Listing Two
public void enumerateAttributes (JcfMember member)
{
  JcfAttributeCollection attrs = member.getAttributes();
  JcfConstantPool cp = member.getConstPool();
  System.out.println("Listing " + attrs.size() + " attributes:");

  Enumeration enum = attrs.elements();
  while (enum.hasMoreElements())
  {
    JcfAttribute attribute = (JcfAttribute)enum.nextElement();
    System.out.println("  " + cp.utfAt(attribute.getNameIndex()));
  }
}


Listing Three
[lti\java\stripdebug\StripDebugClassFile.java]
package lti.java.stripdebug;
import java.io.*;
import lti.java.jcf.*;

public class StripDebugClassFile extends JcfClassFile
{
  public StripDebugClassFile()
    { super(); }
  public StripDebugClassFile (JcfClassInput ist)
    throws IOException, ClassFormatError
    { super(ist); }
  // Override this factory method to return a JcfAttributeCollection subclass.
  public JcfAttributeCollection readAttributes(JcfClassInput ist)
    throws IOException
  { 
    return new StripDebugAttributeCollection(ist, getConstantPool());
  }
}


Listing Four
[lti\java\stripdebug\StripDebugAttributeCollection.java]
package lti.java.stripdebug;
import java.io.*;
import lti.java.jcf.*;

public class StripDebugAttributeCollection   extends JcfAttributeCollection
{
  public void write (JcfClassOutput ost)     throws IOException
  {
    String attribName;
    int total = size();
    for (int i = 0; i < total; i++) {
      attribName = constPool.utfAt(attributeAt(i).getNameIndex());
      if (attribName.equals("LineNumberTable") ||
        attribName.equals("LocalVariables") ||
        attribName.equals("SourceFile")) 
      { removeElementAt(i); i--; total--; } 
    }
    super.write(ost);
  }
}

2


