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.
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
Popular Articles:
- Programmatically logging using Apache Log4J
- Reading POP3 Mails Using Java
- Understanding Prototype Design Pattern in Java
- Reading New Emails from Java Applications
- Log4J Logging Inside Eclipse Console
- HTTP Form POST Request using AJAX and Servlet
- Remote URL Connection Through Proxy in Java
- Singleton Design Pattern in Java
- Reading Excel Sheet Documents in Java
- MySql Batch Insert/Update in Java


































