Introduction To Javap Tool In Java

Introduction

 
In this article, we discuss the javap command in Java and how to create your own javap command.
 

Javap command in Java

 
The javap command disassembles compiled Java files. The javap command displays information about the variables, constructors, and methods present in a class file. This may be helpful when the original source code is no longer available on a system.
 
The output of javap commands depends on the options used. If you do not specify an option then it simply prints out the package, public fields & protected methods of the class. 
 

Developing a program that just works the same as the javap command

 
The following public methods can be used for displaying metadata of a class.
Method[] getDeclaredMethods() thows SecurityException
 
returns an array of Method objects reflecting all the methods declared by the class or interface represented by this Class object.

Field[] getDeclaredFields() throws SecurityException
 
returns an array of filed objects reflecting all the fields declared by the class or interface represented by this Class object.

Constructor[] getDeclaredConstructor() throws SecurityException
 
return an array of Constructor objects reflecting all the constructors declared by the class represented by the Class object.
Example
  1. import java.lang.reflect.*;  
  2. public class JavapEx {  
  3.  public static void main(String args[]) throws Exception {  
  4.   Class cls = Class.forName(args[0]);  
  5.   System.out.println("Fields are...........");  
  6.   Field fld[] = cls.getDeclaredFields();  
  7.   for (int i = 0; i < fld.length; i++)  
  8.    System.out.println(fld[i]);  
  9.   System.out.println("Constructors are.....");  
  10.   Constructor con[] = cls.getDeclaredConstructors();  
  11.   for (int i = 0; i < con.length; i++)  
  12.    System.out.println(con[i]);  
  13.   System.out.println("Methods are.........");  
  14.   Method mthd[] = cls.getDeclaredMethods();  
  15.   for (int i = 0; i < mthd.length; i++)  
  16.    System.out.println(mthd[i]);  
  17.  }  
  18. }  
 
Output
fig-3.jpg
 
fig-4.jpg