Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Java Reflection: Basic concept and Implementation

In this article we will learn about the basic concepts of java reflection and its implementation in java programming.

Reflection is commonly used by java programs which require the ability to examine or modify the runtime behaviour of applications running in the Java virtual machine (JVM). Or in simple words reflection can be stated as the ability of a program to examine and modify the structure and behaviour of an object at runtime.

The java.lang.Class class and java.lang.ClassLoader provides many methods that can be used to get metadata, examine and change the runtime behaviour of a class. It provides mechanisms for finding the classes at runtime, instantiating instances of the class, locating and executing methods, and accessing data members.

Some useful methods of class Class use in reflection framework are as follows:

  • getConstructor, getConstructors, getDeclaredConstructor
  • getMethod, getMethods, getDeclaredMethods
  • getField, getFields, getDeclaredFields
  • getSuperclass
  • getInterfaces
  • getDeclaredClasses

Reflection enables us to do the following:

  • Examine an object’s class at runtime
  • Construct an object for a class at runtime
  • Examine a class’s field and method at runtime
  • Invoke any method of an object at runtime
  • Change accessibility flag of Constructor, Method and Field

Concept of reflection is often mixed with introspection. The following are their standard definitions:

  • Introspection is the ability of a program to examine the type or properties of an object at runtime.
  • Reflection is the ability of a program to examine and modify the structure and behavior of an object at runtime.

From their definitions, introspection is a subset of reflection. There are many languages which do not support the features.Some other languages support introspection, but do not support reflection like C++.

Advantages of Reflection

  • Reflection has several real time uses; often you are in some conditions where you require the additional information about the class. For example in a networking environment while sending the packets you may need to get information about the sender’s identity, in such scenario reflection is helpful.
  • Another useful real-world use of reflection is when writing a framework that has to interoperate with user-defined classes, where the framework author doesn't know what the members (or even the classes) will be. Reflection allows them to deal with any class without knowing it in advance. This becomes very useful in complex application development.
  • As another example, JUnit used to use a trivial bit of reflection: it enumerates all methods in your class, assuming that all those called testXXX are test methods, and executes them
  • Another practical scenario of reflection: Consider a system that does custom processing on packets of data. What processing will be done on the data depends upon the value of the header field of the packet. What will you do if the processing requirements are dynamic in nature and values that the header-field can have keep changing depending upon customer requirements etc.? Solution is using Reflection. Reflection API enables you to create an instance of a class whose name is not known until runtime. You can just plug-in the custom processing classes into the system, without having to recompile the code again.

Drawbacks of Reflection

Although reflection is very powerful tool in java, but it should be avoided normally. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.

  • Performance Overhead

As we are aware reflection performs its action at runtime and associated with low level of JVM. At that levelcertain Java virtual machine optimizations cannot be performed. In result, reflective operations have slower performance than their non-reflective portions, and should be avoided in sections of code which are called frequently in performance-sensitive applications.

  • Security Restrictions

Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context, such as in an Applet.

Below are some examples of reflection API, where we will be able to fetch information about the classes, their methods, and constructors at runtime.

Listing 1: Get class name from object instance

  package articles;
  import java.lang.reflect.Method;
  import java.lang.*;
   
  public class ReflectionArticleDemo 
  {
      public static void main(String[] args){
        ReflectionArticle objReflectionArticle = new ReflectionArticle ();
        Class objClass = objReflectionArticle.getClass();
        System.out.println(objClass.getName());                             
   }
  }
   
  class ReflectionArticle 
  {
     public void showPrintInfo() {
        System.out.println("Performing operations on this class.");
     }
  }

Output Listing 1: articles.ReflectionArticle

Explanation Listing 1: Here we created an ReflectionArticle class, and in main method we are creating object of this class and by taking help of ‘Class’ class we are fetching information about the ‘ReflectionArticle’ class by utilizing its object. When you execute this program you will be presented the name of the class. getClass() method returns the reference of our ‘ReflectionArticle’ class and store it in the Class object.

Listing 2: Invoke method on unknown object

 
  package articles;
  import java.lang.reflect.Method;
   
  public class ReflectionArticleDemo 
  {
     public static void main(String[] args)
     {
        ReflectionArticle  objReflectionArticle = new  ReflectionArticle ();
        Method method;
        try {
           Class objClass = objReflectionArticle.getClass();
           method = objClass.getMethod("showPrintInfo ", new Class<?>[0]);
           method.invoke(objReflectionArticle);
        }
        catch (Exception e)
         {
           e.printStackTrace();
         }                                                           
        }
  }
   
  class ReflectionArticle 
  {
    public void showPrintInfo() {
      System.out.println("Performing operations on this class.");
    }
  }

Output Listing 2: Performing operations on this class

Explanation Listing 2: Here we created an ReflectionArticle class, and in main method we are creating an object of this class. Using the ‘Class’ class we are fetching information about the ‘ReflectionArticle’ class . getMethod method used to fetch the required method from the class.

Listing 3: Create object from Class instance

 
  package articles;
   
  public class ReflectionArticleDemo {
    public static void main(String[] args){
      //create instance of "Class"
      Class<?> c = null;
      try{
       c=Class.forName("articles. ReflectionArticle ");
      }catch(Exception e){
          e.printStackTrace();
      }
   
      //create instance of " ReflectionArticle "
      ReflectionArticle  objReflectionArticle = null;
   
      try {
        objReflectionArticle = (ReflectionArticle) c.newInstance();
      } catch (Exception e) {
         e.printStackTrace();
      }              
   
      objReflectionArticle. showPrintInfo();
     }
  }
   
  class ReflectionArticle 
  {
     public void showPrintInfo() {
        System.out.println("Performing operations on this class.");
  }
}

Output Listing 3: Performing operations on this class.

Explanation Listing 3: Here we created a ReflectionArticle class. Creating object of class ‘ReflectionArticle’ using Class.forName() method, storing the object of fetched class in type Class and creating new instance of ‘ReflectionArticle’” using newInstance() method.

Listing 4 : Create Instance and calling the constructor

package articles; 
   import java.lang.reflect.Constructor;
   public class ReflectionArticleDemo{
      public static void   main(String[] args){
        //create instance of   "Class"
        Class<?> c = null;
        try{
           c=Class.forName("articles. ReflectionArticle ");
        }catch(Exception   e){
           e.printStackTrace();
        }
    
        //create instance of   " ReflectionArticle "
        ReflectionArticle obj1ReflectionArtcle = null;
        ReflectionArticle obj2 ReflectionArtcle = null;
    
        //get all constructors
        Constructor<?>   cons[] = c.getConstructors();
    
        try {
         obj1ReflectionArtcle = (ReflectionArticle)   cons[0].newInstance();
         obj2ReflectionArtcle = (ReflectionArticle) cons[1].newInstance("Tst");
        } catch (Exception   e) {
          e.printStackTrace();
        }                   
    
        obj1ReflectionArtcle.print();
        obj2ReflectionArtcle.print();
      }
   }
    
   class ReflectionArtcle {
      String s; 
    
      public ReflectionArtcle (){}
    
      public ReflectionArtcle (String s){
       this.s=s;
      }
    
      public void print() {
       System.out.println(s);
      }
   }
}

Output Listing 4:

null
Tst

Explanation Listing 4: As stated in Listing 3 we created a ReflectionArticle class. Creating object of class ‘ReflectionArticle’ using Class.forName() method, storing the object of fetched class in type Class and creating new instance of ‘ReflectionArticle’” using newInstance() method , and calling constructor using getConstructors() method.

Conclusion:

In this tutorial we learned the basic concept of reflection in java, and got the idea how to make use of reflection API and also implemented some of the functionality using reflection classes.



Computer system engineer who has 4 year of experience in the field our web-development ,FPGA, and java programming.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login