Thursday, 10 May 2012

Getting Started With Java Reflection API

So, how do you tell what you look like right now? Unless you are two-headed monster, you are going to use a mirror. Similarly, a Java program examines itself, using the classes available in the java.lang.reflect package.

Here is a simple Java class which has a method describe(), which returns a String description of any class you pass to it.
package com.whycouch;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

 * This is a class that describes classes
 * @version 1.0
 * @author Hathy Ash
public class Describer {

    static String describe(Class c){
        StringBuilder description=new StringBuilder();

        description.append("Description of ")

        // Now listing all the constructors of the class
        Constructor[] constructors=c.getConstructors();
        if(constructors.length>0) {
            description.append("\nIt has ")
                    .append(" constructor(s), namely,\n");
            for(Constructor constructor:constructors){
                description.append(">> ")
        }else {
            description.append("\nIt has no constructors\n");

        // Now listing all the methods of the class
        Method[] methods=c.getDeclaredMethods();
            description.append("\nIt has ")
                    .append(" method(s), namely,\n");
            for(Method method:methods){
                description.append(">> ")
            description.append("\nIt has no methods\n");

        // Now listing all the fields of the class
        Field[] fields=c.getDeclaredFields();
            description.append("\nIt has ")
                    .append(" field(s), namely,\n");
            for(Field field:fields){
                description.append(">> ")
            description.append("\nIt has no fields\n");
        return description.toString();

Now to describe itself (or any other class), all you have to do is, add
public static void main(String[] args){
You will see output like,

Description of com.whycouch.Describer

It has 1 constructor(s), namely,
>> public com.whycouch.Describer()

It has 2 method(s), namely,
>> static java.lang.String com.whycouch.Describer.describe(java.lang.Class)
>> public static void com.whycouch.Describer.main(java.lang.String[])

It has no fields

No comments:

Post a Comment