Sunday, January 26, 2014

Hello world Reflection Example to get the methods and constructors declared in class

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package reflection;

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

/**
 *
 * @author Rishitha
 */
public class ReflectionExample {

    public void requestConstuctors() throws ClassNotFoundException {
        Class cl;
        Constructor con[];
        Method meth[];
        try {
           //You can pass another class name to find out the methods
           //and constructors declared in that class.Provide packagename.classname
           cl = Class.forName("reflection.Test");
            con = cl.getDeclaredConstructors();
            for (int x = 0; x < con.length; x++) {
                System.out.println("Constructor " + x + " = " + con[x]);
            }

            meth = cl.getDeclaredMethods();
            for (int x = 0; x < meth.length; x++) {
                System.out.println("Method " + x + " = " + meth[x]);
            }

        } catch (Exception e) {
           
        e.printStackTrace();
    }    
     }      
       
        

    public static void main(String args[]) throws ClassNotFoundException {
        ReflectionExample req = new ReflectionExample();
        System.out.println("hello ");
        req.requestConstuctors();
    }
}

 class Test{
   
    public Test(){
       
    }
    public Test(String s ){
       
    }
    public String sayHello(){
        return "hello";
    }
    public int getInt(){
        return 1;
    }
   
}

No comments:

Post a Comment