Skip to main content

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:
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();
     }
  }
}
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.

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.

Comments

Popular posts from this blog

Mobile Message Organizer

Got a basic requirement that i think every mobile should have, all the mail clients have this facility and i dont see any big difficulties on this other than the storage problem which is not a problem at all as we got GB of spaces in our memory cards. Well i am talking about the organizing the messages in Inbox , categorization of messages. Suppose i want to store all the messages from one of my friend say A in a folder called Personal, my existing mobile device Nokai E71 doesn't have this feature inbuilt (Ofcourse if you want you can make a folder and move the messages manually but here i am talking about the idea of automating this procedure). Only thing we need to do is , we have to store the rules in separate location , rules will be defined by the user and then device will follow these rules.There are no or very less software available which satisfy this requirement for mobile device.this is so simple but basic requirement as per the end user. I am going to make this one ...

Interview : Shiv Khera

Winning as a way of life Shiv Khera, motivational expert, speaker, consultant and author of three best-selling books, does not necessarily speak about new things. His subject is human life – the individual vis-à-vis society, and how the two can win. But it is the use of the right word at the right time in the right context in simple, evocative terms that sets him apart. Rajeev Nair met him in Dubai Charged – that is one word to describe the infectious persona of Shiv Khera, the motivational expert, hot in demand in the US professional circles to turn around company fortunes and develop the man power base. The Indian has been a US-resident for nearly three decades but hasn’t relinquished his Indian citizenship; he even contested the general elections from Delhi.

Indian Education System : Let's shape it

Good advice is always certain to be ignored, but that's no reason not to give it.                                                                                        By Agatha Christie   This is one of the things that I wanted to write from long back and per my opinion it should be matter of at most important for any educated person of India. Today in this article I would like  focus on reminding people about the importance of education and educational departments  no matter those are government related or privately held. Whatever we are to...