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.

MethodDescription
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

Example of creating javap tool

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

snippet
import java.lang.reflect.*;

public class MyJavap{
   public static void main(String[] args)throws Exception {
	Class c=Class.forName(args[0]);
	
	System.out.println("Fields........");
	Field f[]=c.getDeclaredFields();
	for(int i=0;i<f.length;i++)
		System.out.println(f[i]);
	
	System.out.println("Constructors........");
	Constructor con[]=c.getDeclaredConstructors();
	for(int i=0;i<con.length;i++)
		System.out.println(con[i]);
	
        System.out.println("Methods........");
	Method m[]=c.getDeclaredMethods();
	for(int i=0;i<m.length;i++)
		System.out.println(m[i]);
   }
}

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

Output:

creating a program that works like javap tool creating a program that works like javap tool
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +