Wrapping javap into a java program

Hi All,

This is not homework.

I have Win2k with NT

From what I have seen and tried so far: javap requests are made from a open DOS page, and can be stored in a  file such as  "output.txt"

I would like to issue that javap request from a java program into a  "output.txt".

Sample would be appreciated.

Delphi3
LVL 4
delphi3Asked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
sudhakar_koundinyaConnect With a Mentor Commented:
DumpMethods is used to find the methods of java class

import java.lang.reflect.*;
import java.io.*;
 
   public class DumpMethods {
      public static void main(String args[])
      {
         try {
            FileOutputStream fout=new FileOutputStream("c:\\output.txt");
            Class c = Class.forName(args[0]);
            Method m[] = c.getDeclaredMethods();
            for (int i = 0; i < m.length; i++)
{
          fout.write(m[i].toString().getBytes());
         fout.write("\r\n".getBytes());
}
         }
         catch (Throwable e) {
            System.err.println(e);
         }
      }
   }

here is how you should execute

java DumpMethods java.lang.String

or

java DumpMethods java.util.Vector

the output you see in c:\Output.txt

0
 
sudhakar_koundinyaCommented:
0
 
sudhakar_koundinyaCommented:
Prints the methods to file

   import java.lang.reflect.*;
import java.io.*;
 
   public class DumpMethods {
      public static void main(String args[])
      {
         try {
            FileOutputStream fout=new FileOutputStream("c:\\output.txt");
            Class c = Class.forName(args[0]);
            Method m[] = c.getDeclaredMethods();
            for (int i = 0; i < m.length; i++)
          fout.write(m[i].toString().getBytes());
         fout.write("\r\n".getBytes());
         }
         catch (Throwable e) {
            System.err.println(e);
         }
      }
   }
0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
sudhakar_koundinyaCommented:
import java.lang.reflect.*;

   public class method1 {
      private int f1(
       Object p, int x) throws NullPointerException
      {
         if (p == null)
            throw new NullPointerException();
         return x;
      }
       
      public static void main(String args[])
      {
         try {
           Class cls = Class.forName("method1");
       
            Method methlist[]
              = cls.getDeclaredMethods();
            for (int i = 0; i < methlist.length;
               i++) {  
               Method m = methlist[i];
               System.out.println("name
                 = " + m.getName());
               System.out.println("decl class = " +
                              m.getDeclaringClass());
               Class pvec[] = m.getParameterTypes();
               for (int j = 0; j < pvec.length; j++)
                  System.out.println("
                   param #" + j + " " + pvec[j]);
               Class evec[] = m.getExceptionTypes();
               for (int j = 0; j < evec.length; j++)
                  System.out.println("exc #" + j
                    + " " + evec[j]);
               System.out.println("return type = " +
                                  m.getReturnType());
               System.out.println("-----");
            }
         }
         catch (Throwable e) {
            System.err.println(e);
         }
      }
   }
0
 
delphi3Author Commented:
sudhakar_koundinya,
Please comment on each of your gifts. A run of
DumpMethods shows a empty text file.  What of javap was it accessing?


And run of method1 and similarily what of javap was it accessing ?

As I said earlier I have dumped the DOS statement in to the output.txt by using this DOS statement:

C:\j2sdk1.4.2_05\bin>javap java.awt.AWTKeyStroke>output.txt

I hope that you can clarify.

D3
0
 
sudhakar_koundinyaCommented:
The otherway what you are expecting is this

  try {
        // Execute command
           FileOutputStream fout=new FileOutputStream("c:\\output.txt");
        String command = "c:\\jdk1.4\bin\javap.exe "+class;
        Process child = Runtime.getRuntime().exec(command);
   
        // Get the input stream and read from it
        InputStream in = child.getInputStream();
        int c;
        while ((c = in.read()) != -1) {
              fout.write(c);
        }
        in.close();
    } catch (IOException e) {
    }
0
 
sudhakar_koundinyaCommented:
public class Javap
{
               public static void main(String s[])
             {
try {
        // Execute command
           FileOutputStream fout=new FileOutputStream(args[1]);
        String command = "c:\\jdk1.4\bin\javap.exe "+args[0];
        Process child = Runtime.getRuntime().exec(command);
   
        // Get the input stream and read from it
        InputStream in = child.getInputStream();
        int c;
        while ((c = in.read()) != -1) {
              fout.write(c);
        }
        in.close();
    } catch (IOException e) {
    }
              }
}


Execute like this

java JavaP java.lang.String c:\output.txt
0
 
sudhakar_koundinyaCommented:
import java.io.*;
import java.util.*;

public class Javap {
  /**
   * Usage : java Javap <class name> <output file>
   * Example : java Javap java.lang.String output.txt
   * @param args String[]
   */
  public static void main(String args[]) {
    try {
      // Execute command
      FileOutputStream fout = new FileOutputStream(args[1]);
      String command = "c:\\jdk1.4\\bin\\javap.exe " + args[0];
      Process child = Runtime.getRuntime().exec(command);

      // Get the input stream and read from it
      InputStream in = child.getInputStream();
      int c;
      while ( (c = in.read()) != -1) {
        fout.write(c);
      }
      in.close();
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  }
}
0
 
delphi3Author Commented:
sudhakar_koundinya,

You have overwhelmed me with options and I really thank you for your efforts to show me
the various choices.

A comment on these samples directly above:
      String command = "c:\\jdk1.4\bin\javap.exe "+class;
        Process child = Runtime.getRuntime().exec(command);
   
        // Get the input stream and read from it
        InputStream in = child.getInputStream();
There is an illegal escape character in the String command after the word "bin"...... BUT
please don't correct.  I did not use that.


For the record here: in terms of the implications for javap:
I am using j2sdk1.4.2_05 and have downloaded just one page: the tree view downloaded

from:      http://java.sun.com/j2se/1.4.2/docs/api/
 
But with this list  NOW I can read anyone of the classes are listed in the tree format.  If I

pause for a moment over the class name, the Package from which the class name was a

part of appears.  This is information is a part of the "hint"

This is my program that I give here as part of the record of this Q. You should see  your

efforts in my program. I have Win2K with NT.

Thanks again.

Delphi3

/*
 * Swing Version
 */

import javax.swing.*;
import java.io.*;
import java.awt.*;              //for layout managers
import java.awt.event.*;        //for action and window events
import java.lang.reflect.*;


public class JavapPkgDotClass extends JFrame
  implements ActionListener {
  private String newline = "\n";
  private String pk = "";
  private String cl = "";
 
  JTextArea textArea = new JTextArea();
 
  protected static final String pkgFieldString = "Package Field";
  protected static final String classwordFieldString = "Class Field";
 
  protected JLabel actionLabel;
 
  public JavapPkgDotClass() {
    super("Package Class Javap Lookup");
   
    //Create a regular text field.
    JTextField textField1 = new JTextField(10);
    textField1.setActionCommand(pkgFieldString);
    textField1.addActionListener(this);
   
    //Create a password field.
    JTextField textField2 = new JTextField(10);
    textField2.setActionCommand(classwordFieldString);
    textField2.addActionListener(this);
   
    //Create some labels for the fields.
    JLabel textFieldLabel1 = new JLabel(pkgFieldString + ": ");
    textFieldLabel1.setLabelFor(textField1);
    JLabel textFieldLabel2 = new JLabel(classwordFieldString + ": ");
    textFieldLabel2.setLabelFor(textField2);
   
    //Create a label to put messages during an action event.
    actionLabel = new JLabel("Type text and then Return in each field.");
    actionLabel.setBorder(BorderFactory.createEmptyBorder(10,0,0,0));
   
    //Lay out the text controls and the labels.
    JPanel textControlsPane = new JPanel();
    GridBagLayout gridbag = new GridBagLayout();
    GridBagConstraints c = new GridBagConstraints();
   
    textControlsPane.setLayout(gridbag);
   
    JLabel[] labels = {textFieldLabel1, textFieldLabel2};
    JTextField[] textFields = {textField1, textField2};
    addLabelTextRows(labels, textFields, gridbag, textControlsPane);
   
    c.gridwidth = GridBagConstraints.REMAINDER; //last
    c.anchor = GridBagConstraints.WEST;
    c.weightx = 1.0;
    gridbag.setConstraints(actionLabel, c);
    textControlsPane.add(actionLabel);
    textControlsPane.setBorder(
                               BorderFactory.createCompoundBorder(
                                                                  BorderFactory.createTitledBorder("Text

Fields"),
                                                                 

BorderFactory.createEmptyBorder(5,5,5,5)));
   
    //Create a text area.
   
    textArea.setFont(new Font("Serif", Font.ITALIC, 16));
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);
    JScrollPane areaScrollPane = new JScrollPane(textArea);
    areaScrollPane.setVerticalScrollBarPolicy(
                                              JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    areaScrollPane.setPreferredSize(new Dimension(550, 250));
    areaScrollPane.setBorder(
                             BorderFactory.createCompoundBorder(
                                                                BorderFactory.createCompoundBorder(
                                                                                                   

BorderFactory.createTitledBorder("From Javap "),
                                                                                                   

BorderFactory.createEmptyBorder(5,5,5,5)),
                                                                areaScrollPane.getBorder()));
   
    //Put everything in the applet.
    JPanel leftPane = new JPanel();
    BoxLayout leftBox = new BoxLayout(leftPane, BoxLayout.Y_AXIS);
    leftPane.setLayout(leftBox);
    leftPane.add(textControlsPane);
    leftPane.add(areaScrollPane);
   
    JPanel contentPane = new JPanel();
    BoxLayout box = new BoxLayout(contentPane, BoxLayout.X_AXIS);
    contentPane.setLayout(box);
    contentPane.add(leftPane);
    setContentPane(contentPane);
  }
 
  private void addLabelTextRows(JLabel[] labels,
                                JTextField[] textFields,
                                GridBagLayout gridbag,
                                Container container) {
    GridBagConstraints c = new GridBagConstraints();
    c.anchor = GridBagConstraints.EAST;
    int numLabels = labels.length;
   
    for (int i = 0; i < numLabels; i++) {
      c.gridwidth = GridBagConstraints.RELATIVE; //next-to-last
      c.fill = GridBagConstraints.NONE;      //reset to default
      c.weightx = 0.0;                       //reset to default
      gridbag.setConstraints(labels[i], c);
      container.add(labels[i]);
     
      c.gridwidth = GridBagConstraints.REMAINDER;     //end row
      c.fill = GridBagConstraints.HORIZONTAL;
      c.weightx = 1.0;
      gridbag.setConstraints(textFields[i], c);
      container.add(textFields[i]);
    }
  }
 
  public void actionPerformed(ActionEvent e) {
    String prefix = "You typed \"";
   
    if (e.getActionCommand().equals(pkgFieldString)) {
      JTextField source1 = (JTextField)e.getSource();
      actionLabel.setText(prefix + source1.getText() + "\"");
      System.out.println(source1.getText());
      pk = source1.getText();
     
    }else{
     
      JTextField source2 = (JTextField)e.getSource();
      actionLabel.setText(prefix + new String(source2.getText())
                            + "\"");
      System.out.println(source2.getText());
      cl = source2.getText();
     
      String pkDotcl = pk + "."+ cl;
      System.out.println(pkDotcl);
     
      if (pk != ""&& cl != "")  {
        try {
          FileOutputStream fout=new FileOutputStream(pkDotcl + " output.txt");
          Class c = Class.forName(pkDotcl);
          Method m[] = c.getDeclaredMethods();
          int cnt =  m.length;
          textArea.append(pkDotcl + newline + newline );
          for (int i = 0; i < m.length; i++){            
            fout.write(m[i].toString().getBytes());
            fout.write("\r\n".getBytes());
            textArea.append(m[i].toString() + newline);
          }            
          fout.close();
          textArea.append(newline + newline );
        }
        catch (Throwable r) {
          System.err.println(r);
         
        }        
      }
    }
  }    
 
  public static void main(String[] args) {
    JFrame frame = new JavapPkgDotClass();
   
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
   
    frame.pack();
    frame.setVisible(true);    
  }  
}

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.