Creating a program that works as javap tool

Creating custom javap tool in java, listing classes, methods and constructor in java, example of creating javap tool, reflection in java, Class class, creating appletviewer tool, accessing private method etc.

Creating a program that works as javap tool

Creating a program that works as javap tool

Following methods of java.lang.Class class can be used to display the metadata of a class.

Method Description
public Field[] getDeclaredFields()throws SecurityException returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object.
public Constructor[] getDeclaredConstructors()throws SecurityException returns an array of Constructor objects reflecting all the constructors declared by the class represented by this Class object.
public Method[] getDeclaredMethods()throws SecurityException returns an array of Method objects reflecting all the methods declared by the class or interface represented by this Class object.

Example of creating javap tool

Let's create a program that works like javap tool.

  1. import java.lang.reflect.*;  
  2.   
  3. public class MyJavap{  
  4.    public static void main(String[] args)throws Exception {  
  5.     Class c=Class.forName(args[0]);  
  6.       
  7.     System.out.println("Fields........");  
  8.     Field f[]=c.getDeclaredFields();  
  9.     for(int i=0;i<f.length;i++)  
  10.         System.out.println(f[i]);  
  11.       
  12.     System.out.println("Constructors........");  
  13.     Constructor con[]=c.getDeclaredConstructors();  
  14.     for(int i=0;i<con.length;i++)  
  15.         System.out.println(con[i]);  
  16.       
  17.         System.out.println("Methods........");  
  18.     Method m[]=c.getDeclaredMethods();  
  19.     for(int i=0;i<m.length;i++)  
  20.         System.out.println(m[i]);  
  21.    }  
  22.  

At runtime, you can get the details of any class, it may be user-defined or pre-defined class.