Solved

Wrapping javap into a java program

Posted on 2004-09-29
9
367 Views
Last Modified: 2006-11-17
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
0
Comment
Question by:delphi3
  • 7
  • 2
9 Comments
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12182233
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12182255
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
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12182281
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 4

Author Comment

by:delphi3
ID: 12183061
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
 
LVL 14

Accepted Solution

by:
sudhakar_koundinya earned 50 total points
ID: 12183188
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
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12183342
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
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12183373
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
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12183577
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
 
LVL 4

Author Comment

by:delphi3
ID: 12221737
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

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
tomcat administrtor 12 68
Fast way to search item into Java Array (Rhino compatible) 2 36
junit as external jar or library 7 37
Java array 10 55
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

713 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question