Home | Login | Blog | Forum | Download | RSS Feed | Ajax | Hello-World | J2EE | BPM | EJB | FileNet | Hibernate | ORM | IBM | ILOG | Interview | FAQs |

Java | Apache | JVM | Others | BRMS | Oracle | Pega | SOA | Sun-Certification | Web-Service | websphere | XML |
 

JAVA DEVELOPER SITE - COMPLETE JAVA TUTORIALS

Java Reflection API Samples and Tutorial for Beginners


Share
 
 

Useful Java Links


       


  • Java Reflection is a feature in Java which allows Java programs to introspect upon itself and manipulate the internal properties of the program. Ii is a way of thinking its a metalanguage that enables you to analyze and manipulate your objects in a dynamic way.
  • Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine.It gives the runtime information about the objects classes and interfaces.
  • The reflection API is used  if we are writing development tools such as debuggers, class browsers, and GUI builders
  • Reflection answers questions like :

§  Which class does an object belongs to ?

§  What is the description of a given class name?

§  What are the fields in the given clas

§  What is the type of a field?

§  What are the methods in a class?

§  What are the parameters of a method?

§  What are the constructors of a given class?

                                   

  • Reflection also do things like

·         Constructing an object using a given Constructor.

·         Invoking a object's method using such-and-such parameters

·         Assigning value to an object field.

·         Dynamically creating and manipulating arrays

 

 

  • For each class, the Java Runtime Environment (JRE) maintains an immutable Class object that contains information about the class. A Class object represents, or reflects, the class. With the reflection API, we can invoke methods on a Class object which return Constructor, Method, and Field objects.
  • We can use these objects to get information about the corresponding constructors, methods, and fields defined in the class.  Class objects also represent interfaces. We invoke Class methods to find out about an interface's modifiers, methods, and public constants. Not all of the Class methods are appropriate when a Class object reflects an interface. For example, it doesn't make sense to invoke getConstructors when the Class object represents an interface.

 

A program to explain the  Java Reflection API

 

import java.lang.reflect.*;

import java.awt.*;

 

class SampleName {

private double d;

public static final int i = 37;

private  String s = "testing";

private int x,y;

 

public SampleName(){

            System.out.println("Constructor1");

}

public SampleName(int x){

            this.x=x;

}

public SampleName(int x,int y){

            this.x=x;

            this.y=y;

}

   public static void main(String[] args) {

           

            Button b = new Button();

           

            try {

            Class cls = Class.forName("SampleName");

            System.out.println("Finding Out About Class Fields");

            Field fieldlist[]

              = cls.getDeclaredFields();

            for (int i= 0; i < fieldlist.length; i++) {

               Field fld = fieldlist[i];

               System.out.println("name= " + fld.getName());

               System.out.println("decl class = " +

                           fld.getDeclaringClass());

               System.out.println("type = " + fld.getType());

               int mod = fld.getModifiers();

               System.out.println("modifiers = " +

                          Modifier.toString(mod));

               System.out.println("-----");

            }

            System.out.println("Invoking Methods by Name");

                        Class partypes[] = new Class[2];

            partypes[0] = Integer.TYPE;

            partypes[1] = Integer.TYPE;

            Method meth = cls.getMethod("add", partypes);

            SampleName methobj = new SampleName ();

            Object arglist[] = new Object[2];

            arglist[0] = new Integer(37);

            arglist[1] = new Integer(47);

            Object retobj

              = meth.invoke(methobj, arglist);

            Integer retval = (Integer)retobj;

            System.out.println(retval.intValue());

 

            System.out.println("Obtaining Information About Constructors");

            Constructor ctorlist[]

               = cls.getDeclaredConstructors();

         for (int i = 0; i < ctorlist.length; i++) {

               Constructor ct = ctorlist[i];

               System.out.println("name  = " + ct.getName());

               System.out.println("decl class = " +

                            ct.getDeclaringClass());

               Class pvec[] = ct.getParameterTypes();

               for (int j = 0; j < pvec.length; j++)

                  System.out.println("param #"

                     + j + " " + pvec[j]);

               Class evec[] = ct.getExceptionTypes();

               for (int j = 0; j < evec.length; j++)

                  System.out.println(

                    "exc #" + j + " " + evec[j]);

               System.out.println("-----");

         }

         System.out.println("Creating New Objects");

 

                Class partypes1[] = new Class[2];

                             partypes1[0] = Integer.TYPE;

                 partypes1[1] = Integer.TYPE;

                Constructor ct1 = cls.getConstructor(partypes1);

                Object arglist1[] = new Object[2];

                   arglist1[0] = new Integer(37);

                   arglist1[1] = new Integer(47);

                    Object retobj1 = ct1.newInstance(arglist1);

 

                    System.out.println("Using Arrays");

            Class cls1 = Class.forName("java.lang.String");

              Object arr = Array.newInstance(cls1, 10);

                        Array.set(arr, 5, "this is a test");

              String s = (String)Array.get(arr, 5);

              System.out.println(s);

 

         

          }

          catch (Throwable e) {

             System.err.println(e);

          }

          System.out.println("Getting the Class Name");

            printName(b);// Getting the Class Name

            SampleName sName=new SampleName();

            System.out.println("Discovering Class Modifiers");

    printModifiers(sName.s);// Discovering Class Modifiers

           

 

   }

   public int add(int a, int b)

             {

               return a + b;

            }

 public  static void printName(Object o) {

         Class c = o.getClass();//retrieving a class object

            String s = c.getName();//name of a Class object by

                                           //invoking the getName method

 

            System.out.println(s);

}

public static void printModifiers(Object o){

Class c = o.getClass();

int m= c.getModifiers();

if(Modifier.isPublic(m))

System.out.println("public");

if(Modifier.isAbstract(m))

System.out.println("Abstract");

if(Modifier.isFinal(m))

System.out.println("final");

}

}

 

 

Output of the above program

 

 

inding Out About Class Fields

name= d

decl class = class SampleName

type = double

modifiers = private

-----

name= i

decl class = class SampleName

type = int

modifiers = public static final

-----

name= s

decl class = class SampleName

type = class java.lang.String

modifiers = private

-----

name= x

decl class = class SampleName

type = int

modifiers = private

-----

name= y

decl class = class SampleName

type = int

modifiers = private

-----

Invoking Methods by Name

Constructor1

84

Obtaining Information About Constructors

name  = SampleName

decl class = class SampleName

-----

name  = SampleName

decl class = class SampleName

param #0 int

-----

name  = SampleName

decl class = class SampleName

param #0 int

param #1 int

-----

Creating New Objects

Using Arrays

this is a test

Getting the Class Name

java.awt.Button

Constructor1

Discovering Class Modifiers

public

final

 

Drawbacks of Reflection

  • Performance Overhead
  • Security Restrictions
  • Exposure of Internals



Download Latest Java/J2EE eBooks, SCJP Dumps, SCWCD Dumps, Pega Tutorial, IBM WebSphere BPM tutorials and many more


If you need any urgent assistance on java-reflection-API-tutorial-for-beginners, kindly email your requirement to us at : info@javagenious.com or Contact-an-Expert. Our experts will try their best to solve your problem.

You can also subscribe to our newsletters on java-reflection-API-tutorial-for-beginners, to receive updates on java-reflection-API-tutorial-for-beginners,via email.Enter you email below:

Enter your email address:

Delivered by FeedBurner



Keyword Tags: java-reflection-API-tutorial-for-beginners tutorial,java-reflection-API-tutorial-for-beginners in java,Concepts of java-reflection-API-tutorial-for-beginners,Java,J2EE,Interview Questions,java-reflection-API-tutorial-for-beginners Examples


Comments:


Post Your Comment:

*

Yes, I would like to recieve email notifications on my reply.

Popular Posts:

 
Popular Downloads

SCJP 1.6 Dumps
JSP Interview Questions
Struts Interview Questions
Hibernate Interview Questions
SCWCD Dumps
SCBCD Dumps

Java/J2EE Tutorial
JMS Tutorials
seam richfaces tutorial
richfaces live demo
jquery example demo
JQuery Tutorial and Source Code
JSF Tutorial
XSL Tutorial
J2EE JMS
CORBA Applications
Java CERTIFICATION
SCJP 1.5
SCJP 1.6
SCWCD 1.5
SCBCD
Mis
Ajax autosuggest autocomplete from database
Struts forms and validation with webflow
Java Apache POI Examples
JDBC Tutorial
Oracle 9i & 10g
MYSQL Tutorial
php Tutorial
JQuery Examples
Upload Java File
JAXB Examples
PL-SQL Tutorial
Dojo AJAX
EJB Examples
Java IDE
Eclipse
NetBeans
IBM Rational Weblogic Workshop
Downloads
SCJP 1.6 Dumps
SCJP 1.5 DUMP
SCJP Material
SCWCD
Java Security
SCBCD Dumps
External Links
SUN Java
JOracle
IBM
PHP Certification
Technical Interview Questions
Amazon Interview Questions
Google Interview Questions
Microsoft Interview Questions
IBM Interview Questions
Yahoo Interview Questions
All Tutorials
php mysql tutorial
SCJP 1.5/1.6
SCWCD 1.5/1.6
Polymorphism
Thread Tutorial
Generics & Exceptions
Spring Struts Hibernate
Java Collections
MAP
SET
LIST
VECTOR
Advanced Java
Stateless Session Bean
Introduction to EJB
Stateful Session Bean
Java Design Patterns
HOME | FORUM | ABOUT | BLOGS | CONTACT-US