Home > Java > Invoking Class Methods using Reflection in Java

Invoking Class Methods using Reflection in Java

Sometimes we want the code should be dynamic and we even want to call the class methods dynamically. This article describes on how we can invoke the class methods dynamically using variables.

To achieve the above operation we use the concept of Reflection in Java. Here in this article i am using 2 java files, Client.java and Server.java. Server.java will be the class that we want to load dynamically and Client.java will have the code responsible for calling the Server class dynamically.

Server.java:

public class Server {
    private int PORT = 0;
 
    public Server() {
	System.out.println("Inside Server Class");
    }
 
    public void setPort(int portno) {
        this.PORT = portno;
    }
 
    public int getPort() {
        return this.PORT;
    }
}

This class is basically an bean structure having getter and setter methods.

Your email:

 


Client.java:

import java.lang.reflect.Method;
 
public class Client {
   public static void main(String args[]) {
      try {
         Class dynamicClass = null;
         dynamicClass = Class.forName("Server");
 
         //Loading methods parameters
         Class[] parameter=new Class[1];
         parameter[0]=int.class;
 
         Object iClass = dynamicClass.newInstance();
 
         //Loading and Invoking setPort method with argument passed	
         Method thisMethod = dynamicClass.getMethod("setPort", parameter);
         thisMethod.invoke(iClass, 6000);
 
         //Loading and invoking getPort method withour argument passed, this method also returns int value
         Method thisMethod1 = dynamicClass.getMethod("getPort", null);
	 int data = (Integer) thisMethod1.invoke(iClass);
 
         System.out.println(data);  
      } catch (ClassNotFoundException e) {
	   e.printStackTrace();
      } catch (SecurityException e) {
           e.printStackTrace();
      } catch (InstantiationException e) {
           e.printStackTrace();
      } catch (IllegalAccessException e) {
           e.printStackTrace();
      } catch (IllegalArgumentException e) {
           e.printStackTrace();
      } catch (Exception e) {
           e.printStackTrace();
      }
   }
}

Here if you see i am initially loading the Server.class dynamially, than i am calling setPort() method and passing 6000 value as an argument. Than i am reading the port value set.

Output:

Inside Server Class
6000


Custom Search

Popular Articles:

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • email
  • IndianPad
  • LinkedIn
  • Live
  • MySpace
  • Netvibes
  • RSS
  • Technorati
  • Yahoo! Bookmarks
  • Yahoo! Buzz
  • Reddit
  • Add to favorites
  • PDF
  • Twitter
Categories: Java Tags:
  1. No comments yet.
  1. No trackbacks yet.