Solved

Wrapping javap into a java program

Posted on 2004-09-29
9
363 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
Comment Utility
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
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
Comment Utility
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
 
LVL 4

Author Comment

by:delphi3
Comment Utility
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
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 14

Accepted Solution

by:
sudhakar_koundinya earned 50 total points
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Suggested Solutions

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

771 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now