Skip to main content

Posts

Showing posts from September, 2009

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 metho