dcsimg
December 8, 2016
Hot Topics:

User Code: Method Finder

  • May 30, 2001
  • By Kishore AR
  • Send Email »
  • More Articles »

While learning Java, I often wished there was a convenient way to find out the constructors, methods and fields of a given Java class. Java's documentation is very good, of course, but you have to follow many links before you finally reach your destination. So I took some time out and worked on a handy solution. The Method Finder is an application that shows you the constructors, methods and fields of a class. It greatly helped me. I hope it will do so for you, too.

Here's the code:


/*  MethodFinder.java
 *  The method finder application
 *  developed by Kishore [kishorear@hotmail.com]
 */

import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.*;

/*
 *  The method finder class makes an instance
 *  of MainFram class and shows the frame
 */

public class MethodFinder
   {
     public static void main(String Args[])
       {  MainFrame f = new MainFrame();	

          f.setSize(560, 410);
          f.centreForm();
          f.setVisible(true);
       }			// end of main
   }				// end of MethodFinder class

and...


/*  Msgbox.java
 *  The method finder application
 */

import java.awt.*;
import java.awt.event.*;

/*  This class displays a custom message
 *  in a dialog box
 */

public class Msgbox extends Dialog 
   {  Msgbox(Frame f1, String prompt, String title)
        { 
          super(f1, title, true);
          setLayout(null);
          setResizable(false);          
          setBackground(SystemColor.control);

          // get width of prompt
          FontMetrics fm = getFontMetrics(getFont());
          int sw = fm.stringWidth(prompt);         

          setSize(sw + 50, 100);

          Dimension d = getSize();

          int a1 = (int) d.getWidth();
          int promptLeft = (a1 - sw) / 2;
           
          Label l1 = new Label();
          l1.setText(prompt);
          l1.setBounds(promptLeft, 30, sw, 20);
          add(l1);

	  Button b1 = new Button();
          b1.setLabel("OK");
          b1.setBounds(0, 0, 40, 20);  
         
          int a = (int) d.getWidth();
          int b = b1.getWidth();
          int c = (a - b) / 2;
          
          b1.setLocation(c, 60);
          
          b1.addActionListener(new ActionListener()
              {  public void actionPerformed(ActionEvent ae)
                   {  setVisible(false);
                   }
              });
           
          add(b1); 

          addWindowListener(new WindowAdapter()
             {  public void windowClosing(WindowEvent we)
                  {   setVisible(false);
                  }
              });
          
          centreForm(); 
          setVisible(true);          
        } 	// End of constructor	

     public void centreForm()
        { Toolkit tkMsg = getToolkit();
          Dimension dimScreen = tkMsg.getScreenSize();
          Dimension dimDialog = getSize();
          int left = (int) (dimScreen.getWidth() - dimDialog.getWidth()) / 2;
          int top = (int) (dimScreen.getHeight() - dimDialog.getHeight()) / 2;
          setLocation(left, top);
        }	// End of centreForm

   }		// End of class

and...


/*  MainFrame.java
 *  The method finder application
 */

import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.*;
import java.awt.datatransfer.*;

/* This class does most of the work of
 * Method Finder. 
 */

class MainFrame extends Frame
   { 
     final int     HIST_COUNT     = 10;
     Choice        chsTypes       = new Choice();	// Choice to select types (constructors, fields, methods)
     TextField     txtClass       = new TextField();	// TextField where user types the name of class
     List          lstValues      = new List();		// List which displays then Constructors, methods or fields
     TextArea      txtFullString  = new TextArea();	// TextArea which displays Description
     Method        myMethods[];				// Method array which holds info about methods of the class
     Field         myFields[];				// Field array which holds info about fields
     Constructor   myConstructors[];			// Constructor array which holds info about constructors
     Button        btnClose;     			// Button which closes the frame
     Button	   btnHelp;				// Button which shows help when clicked
     Checkbox      chkShowDeclaration;			// Checkbox which helps user to switch between actual declaration 
                                                        // and description of method
     PopupMenu     pm;
     String        arrHistory[]   = new String[HIST_COUNT];
     int           currentHist    = 0; 
     Button        btnHistory;
     PopupMenu     pmHistory;

     MainFrame()			
       { super("Method Finder");
         setLayout(null);
         setResizable(false);
         setBackground(SystemColor.control); 	 

         // add first label 
         Label l1 = new Label("Enter a Java Class (like java.awt.Dimension) and press Enter.");
         l1.setBounds(20, 30, 450, 20);         
         add(l1);
         
         // add txtClass
	 txtClass.setBounds(20, 50, 400, 20);
         add(txtClass);
         
         // add btnHistory
         btnHistory = new Button("  /");
         btnHistory.setBounds(400, 50, 50, 20);
         add(btnHistory);
         
         
         // add second label
         Label l2 = new Label("Select an item from the list.");
         l2.setBounds(20, 70, 450, 20);
         add(l2);         
         
         // add chstypes
         chsTypes.setBounds(20, 90, 450, 20); 
         chsTypes.add("Constructers");
         chsTypes.add("Methods");
         chsTypes.add("Fields");
	 add(chsTypes);

         // add next label 'Members'
         Label l3 = new Label("Members");
         l3.setBounds(20, 120, 450, 20);
         add(l3);            

         // add lstValues 
         lstValues.setBounds(20, 140, 450, 100);
         add(lstValues);

         // add label 'Description'
         Label l4 = new Label("Description");
         l4.setBounds(20, 250, 450, 20);
         add(l4);

         // add txtFullString                  
         txtFullString.setBounds(20, 270, 450, 100);
         add(txtFullString);   

         // add Close button
         btnClose = new Button("Close");
         btnClose.setBounds(480, 50, 60, 20);
         add(btnClose);
	
	 // add Help button
	 btnHelp = new Button("Help");
	 btnHelp.setBounds(480, 90, 60, 20);
	 add(btnHelp);
	 
	 // add check box 'Show Actual Declaration'
         chkShowDeclaration = new Checkbox("Show Actual Declaration in Description",false);
         chkShowDeclaration.setBounds(20, 380, 450, 20);
         add(chkShowDeclaration);          
         chkShowDeclaration.setEnabled(false);

	 // add popup menu to lstValues
         pm = new PopupMenu();
         MenuItem mnuZoom = new MenuItem("Zoom...");
         MenuItem mnuCopy = new MenuItem("Copy");
         pm.add(mnuZoom);
         pm.add(mnuCopy);



	 // actionperfomed event mnuCopy (copy to clipboard)
         mnuCopy.addActionListener(new ActionListener()
            {
              public void actionPerformed(ActionEvent ae)
                { 
                  StringSelection ss = new StringSelection(lstValues.getSelectedItem());
                  Toolkit tk = getToolkit();
                  Clipboard cp = tk.getSystemClipboard();
                  cp.setContents(ss, ss);                  
                }
             });
         
         mnuZoom.addActionListener(new ActionListener()
             {
             	public void actionPerformed(ActionEvent ae)
             	 { 
             	   zoomClass();
             	 }
              });

         lstValues.add(pm);  

         // mouse released event of lstValues
         lstValues.addMouseListener(new MouseAdapter()
           {   public void mouseReleased(MouseEvent me)
                  {  
                     // if right button is clicked
                     // and at lstValues has at least one item	
                     if (me.isPopupTrigger() && lstValues.getItemCount() !=0)
                       { 
                         Label tmpLbl = new Label();
                         add(tmpLbl);
                         tmpLbl.add(pm);
                         pm.show(tmpLbl, me.getX() + lstValues.getX(), me.getY() + lstValues.getY());
                       }
                  }
           });
       
         // actionPerformed event of lstValues
         lstValues.addActionListener(new ActionListener()
           {
             public void actionPerformed(ActionEvent ae)
               {
               	 zoomClass();
               }
           });
           
         // add History popup menu
         pmHistory = new PopupMenu();
         pmHistory.addActionListener(new ActionListener()
            {  
            	public void actionPerformed(ActionEvent ae)
            	  {
            	  	txtClass.setText(ae.getActionCommand());
            	  	fillItems();
            	  }
            });
         
         btnHistory.addActionListener(new ActionListener()
             {
             	public void actionPerformed(ActionEvent ae)
             	  {  
             	     Label lbl1 = new Label("lbl1");
             	     add(lbl1);
             	     lbl1.add(pmHistory);
             	     
             	     // add menuitems to pmHistory
             	     pmHistory.removeAll();
             	     //for(int i=0; i=0; i--)
             	        { 
             	          pmHistory.add(arrHistory[i]);
             	        }
                     
             	     int x = btnHistory.getX();
             	     int y = btnHistory.getY() + btnHistory.getHeight();
             	     pmHistory.show(lbl1, x, y);
             	   }
             });
             
         
         // action performed event of txtClass
         txtClass.addActionListener(new ActionListener()
            {  public void actionPerformed(ActionEvent ae) 
                {  fillItems();
                }    
            });

         // item state changed event of chsTypes 
         chsTypes.addItemListener(new ItemListener()
            {  public void itemStateChanged(ItemEvent ie)
                {  fillItems();
                }
            });     

         // item changed event of LstValues
         lstValues.addItemListener(new ItemListener()
            {  public void itemStateChanged(ItemEvent ie)
                {  displayFullText();
                }
            });

         // window closing event
         addWindowListener(new WindowAdapter()
           {  public void windowClosing(WindowEvent we)
                 {  System.exit(0);
                 }
           });

         // action performed event of btnClose
         btnClose.addActionListener(new ActionListener()
           {  public void actionPerformed(ActionEvent ae)
                 { System.exit(0);
                 }
           });

	 // action performed event of btnHelp
	 btnHelp.addActionListener(new ActionListener()
	   {
	     public void actionPerformed(ActionEvent ae)
	         {
	           HelpFrame helpFrame = new HelpFrame(MainFrame.this, "Help.txt");
	           helpFrame.showHelp();
	         }
	    });
	 
         // item state changed event of chkShowDeclaration 
         chkShowDeclaration.addItemListener(new ItemListener()
           {  public void itemStateChanged(ItemEvent ie)
                 { displayFullText();
                 }
           });  
       }				// End of Sample frame constructer
     private void fillItems()
       {
          try
            { 
               txtFullString.setText(" ");
               
               // trim txtClass
               txtClass.setText(txtClass.getText().trim());
 
               // exit if class name is blank 
               if (txtClass.getText().equals(" ") || txtClass.getText().equals(""))
                    return;
               
               // set cursor to hourglass
               setCursor(new Cursor(Cursor.WAIT_CURSOR));               
          
               Class c;
               c = Class.forName(txtClass.getText());
              
               switch (chsTypes.getSelectedIndex())
                 { case 0:  		// Fill Constructers
                     { 
                         // add constructers to list
                         lstValues.removeAll();         
	                 myConstructors = c.getConstructors();
                         for(int i = 0; i < myConstructors.length; i++)
                             lstValues.add(" " + myConstructors[i].getName());

                         break;
                     }			
	           case 1:		// Fill Methods
                     {
                        // add methods to list
                        lstValues.removeAll();
                        myMethods = c.getMethods();
                        for(int i=0; i < myMethods.length; i++)
                            lstValues.add(" " + myMethods[i].getName());

                        break;
                     } 			
                   case 2:		// Fill fields
                     {
                       // add fields to list 
                       lstValues.removeAll();
                       myFields = c.getFields();
                       for (int i=0; i < myFields.length; i++)
                           lstValues.add(" " + myFields[i].getName());
                       //prevChkValue = chkShowDeclaration.getState(); 

                       break;   
                     } 			
                 }			// end of switch
                 
               
               // select first item from lstValues
               if (lstValues.getItemCount() > 0)
                  {   
                    lstValues.select(0);
                    displayFullText();
                    chkShowDeclaration.setEnabled(true);  
                  } 
               else
                    chkShowDeclaration.setEnabled(false);
               
               
               // add to history array
               addToHistory();
               
               setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
  
            } catch (ClassNotFoundException e)	// catch class not found exception
                 { 
                   lstValues.removeAll();   
                   txtFullString.setText(" ");
                   chkShowDeclaration.setEnabled(false);
                   Msgbox m1 = new Msgbox(this, "Invalid Class Name", "Method Finder");
                   setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                 }
              catch (Exception e)		// catch other exceptions
                 {
                   lstValues.removeAll();   
                   txtFullString.setText(" ");
                   chkShowDeclaration.setEnabled(false);
                   Msgbox m1 = new Msgbox(this, "Error" + e, "Method Finder");
                   setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                 }
             
       }   				// end of fill items

     private void displayFullText()
       {    
           switch (chsTypes.getSelectedIndex())
             {   case 0:		// constructors
                    {   Constructor tmpCon = myConstructors[lstValues.getSelectedIndex()];
                        if (chkShowDeclaration.getState())
                            txtFullString.setText(" " + tmpCon);
                        else
                            displayConstructorInfo(tmpCon); 
                        break;
                    }
                 case 1:		// methods
                    {   Method tmpMet = myMethods[lstValues.getSelectedIndex()];
                        if (chkShowDeclaration.getState())
                            txtFullString.setText(" " + tmpMet);
                        else
                            displayMethodInfo(tmpMet);
                        break;
                    } 
                 case 2:		// fields
                    {   Field tmpFie = myFields[lstValues.getSelectedIndex()];
                        if (chkShowDeclaration.getState())
                            txtFullString.setText(" " + tmpFie);
                        else
                            displayFieldInfo(tmpFie);
                        break;
                    }     
             }				// end of switch
       }				// end of displayFullText

     private void displayConstructorInfo(Constructor tmpCon)
       {  
          // get name of constructor
          //String desc = "Name : " + tmpCon.getName();

          // get parameters of constructor
          String desc = "Parameters :- n";
          Class p[] = tmpCon.getParameterTypes();
          for (int i=0; i < p.length; i++)
             desc += "t" + p[i] + "n";

          // get modifiers
          desc += "Modifiers :-n";
          int x = tmpCon.getModifiers();
          desc += getModifierString(x); 

          // get exception types
          desc += "Exception Types :-n";
          Class e[] = tmpCon.getExceptionTypes();
          for (int i=0;  i < e.length; i++)
             desc += "t" + e[i] + "n"; 

          // display information
          txtFullString.setText(desc);
       }           			// end of displayConstructorInfo

     private void displayMethodInfo(Method tmpMet)
       {  
          // get parameter types of method
          String desc = "Parameters :-n";
          Class p[] = tmpMet.getParameterTypes();
          for (int i=0; i < p.length; i++)
             desc += "t" + p[i] + "n";

          // get return type
          desc += "Return Type :-nt" + tmpMet.getReturnType() + "n"; 

          // get modifiers
          desc += "Modifiers :-n";
          int x = tmpMet.getModifiers();
          desc += getModifierString(x);

          // get exception types
          desc += "Exception Types :-n";
          Class e[] = tmpMet.getExceptionTypes();
          for (int i=0;  i < e.length; i++)
             desc += "t" + e[i] + "n"; 
          
          // display information
          txtFullString.setText(desc);            
       }				// end of displayMethodInfo
    
     private void displayFieldInfo(Field tmpField)
       {  String desc;

          // get modifiers
          desc = "Modifiers :-n";
          int x = tmpField.getModifiers();
          desc += getModifierString(x);          

          // display information
          txtFullString.setText(desc);
       }				// end of displayFieldInfo
     
     private String getModifierString(int x)
       {  String strModifier = "";

          if (Modifier.isAbstract(x))		// abstract
             strModifier += "tabstractn";

          if (Modifier.isFinal(x))		// final
             strModifier += "tfinaln";

          if (Modifier.isInterface(x))		// interface
             strModifier += "tinterfacen";

          if (Modifier.isNative(x))		// native
             strModifier += "tnativen";

          if (Modifier.isPrivate(x))		// private
             strModifier += "tprivaten";

          if (Modifier.isProtected(x))		// protected
             strModifier += "tprotectedn";

          if (Modifier.isPublic(x))		// public
             strModifier += "tpublicn";

          if (Modifier.isStatic(x))		// static
             strModifier += "tstaticn";

          if (Modifier.isStrict(x))		// strict
             strModifier += "tstrictn";

          if (Modifier.isSynchronized(x))	// synchronized
             strModifier += "tsynchronizedn";

          if (Modifier.isTransient(x))		// transient
             strModifier += "ttransientn";

          if (Modifier.isVolatile(x))		// volatile
             strModifier += "tvolatilen";

          return(strModifier);
       }				// end of getModifierString
       
     public void addToHistory()
       {  boolean existing = false;
          
          // check if existing
       	  for(int i=0; i= HIST_COUNT)
       	        {   
       	            for(int i=0; i < (HIST_COUNT-1); i++)
       	               arrHistory[i] = arrHistory[i+1];

       	            currentHist--;
       	      	}
       	      
       	      arrHistory[currentHist++] = txtClass.getText();
       	    }	     	      
       }				// end of addToHistory

     private void zoomClass()
      {
        String zoomText = "nClass :- nt" + txtClass.getText();
        zoomText += "nMember :- nt" + lstValues.getSelectedItem();
        zoomText += "n" + txtFullString.getText();
        ZoomFrame zf = new ZoomFrame(MainFrame.this, zoomText);
        zf.zoom();
       }
      	
       	
     public void centreForm()
       {  
          Toolkit tkMsg = getToolkit();
          Dimension dimScreen = tkMsg.getScreenSize();
          Dimension dimDialog = getSize();
          int left = (int) (dimScreen.getWidth() - dimDialog.getWidth()) / 2;
          int top = (int) (dimScreen.getHeight() - dimDialog.getHeight()) / 2;
          setLocation(left, top);
       }				// End of centreForm

   }            			// end of MainFrame class 

plus...


import java.awt.*;
import java.awt.event.*;
import java.io.FileInputStream;

public class HelpFrame extends Frame 
  { private TextArea txtDesc;		// TextArea which displays contents of help.txt 
    final int INDENT = 25;		// set top margin
    private byte readBytes[];		// holds the bytes read from help.txt
    
    public HelpFrame(Frame frm, String fileName)
      {  super("Help");		// call constructor of dialog
         setLayout(new BorderLayout());
         setBackground(SystemColor.control);
	 setSize(400, 400);
	 centreForm();
	 
	 try
	  {		 
	    // read from help.txt
            FileInputStream fHelp = new FileInputStream(fileName);
            int totBytes = fHelp.available();
            readBytes = new byte[totBytes];
            fHelp.read(readBytes, 0, totBytes);
            fHelp.close();
            
            String s1 = "";            
            txtDesc = new TextArea("", 0, 0 , TextArea.SCROLLBARS_VERTICAL_ONLY);
            
            // pass bytes to txtDesc
            for (int i=0; i<totBytes; i++)
             {
             	s1 += (char) readBytes[i];
             }
            
            txtDesc.setText(s1);
            
          } catch (Exception e)
             {
             	System.out.println(" " + e);
             }
         	 
         txtDesc.setEditable(false);
         add(txtDesc, BorderLayout.CENTER);
                
         addWindowListener(new WindowAdapter()
           {
             public void windowClosing(WindowEvent we)
               { 
               	setVisible(false);
               }
           });          
       }
       
    public void zoom()
       { 
       	setVisible(true);
       }
       
    private void centreForm()
       {  
          Toolkit tkMsg = getToolkit();
          Dimension dimScreen = tkMsg.getScreenSize();
          Dimension dimDialog = getSize();
          int left = (int) (dimScreen.getWidth() - dimDialog.getWidth()) / 2;
          int top = (int) (dimScreen.getHeight() - dimDialog.getHeight()) / 2;
          setLocation(left, top);
       }				// End of centreForm
    
    public void showHelp()
       {
       	  setVisible(true);
       }
}

and finally...


/*  Msgbox.java
 *  The method finder application
 */

import java.awt.*;
import java.awt.event.*;

public class ZoomFrame extends Frame
  { TextArea txtDesc; 
    final int INDENT = 25;

    public ZoomFrame(Frame frm, String s1)
      {  super("Zoom");
         setLayout(new BorderLayout());
         setBackground(SystemColor.control);
	 setSize(400, 400);
	 centreForm();
	 
         txtDesc = new TextArea("", 0, 0 , TextArea.SCROLLBARS_VERTICAL_ONLY);
         txtDesc.setText(s1);
         add(txtDesc, BorderLayout.CENTER);
                
         addWindowListener(new WindowAdapter()
           {
             public void windowClosing(WindowEvent we)
               { 
               	setVisible(false);
               }
           });
       
           
       }
       
    public void zoom()
       { 
       	setVisible(true);
       }
       
     private void centreForm()
       {  
          Toolkit tkMsg = getToolkit();
          Dimension dimScreen = tkMsg.getScreenSize();
          Dimension dimDialog = getSize();
          int left = (int) (dimScreen.getWidth() - dimDialog.getWidth()) / 2;
          int top = (int) (dimScreen.getHeight() - dimDialog.getHeight()) / 2;
          setLocation(left, top);
       }				// End of centreForm
       
}

Downloads

Download source files = 24K

JAR file = 17K

About the Author

Kishore Ar works for Thomson Cyber Solutions Pvt. Ltd, Trivandrum, Kerala, India as a senior programmer. He says that programming is his profession and hobby. He has been involved in many projects, both Web-based and client/server, for the last four years especially designing and developing database projects using Java, Visual Basic 6, and Oracle 8i. He can be contacted at kishorear@hotmail.com.

[To contribute a code article to Gamelan, please contact kmurphy@internet.com.]






Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date
Rocket Fuel