Choose Your Language

Friday 9 May 2014

Dynamic class loading and invoking its methods

package dynamic;
import java.lang.reflect.Method;
/**
 *
 * @author Aravind Sankaran
 */
public class DynamicClassLoading {
    public static void main(String ar[]){       
        Class noParameter[]={};
        Class stringParameter[]=new Class[1];      
        stringParameter[0]=String.class;       
        try{
            System.out.println("Dynamic Loading");
            Class classLoader=Class.forName("dynamic.Dynamic");
            Object object=classLoader.newInstance();
            Method method=classLoader.getDeclaredMethod("display",noParameter);
            method.invoke(object, null);
            method=classLoader.getDeclaredMethod("display", stringParameter);
            method.invoke(object,"Aravind");
           
        }catch(Exception e){
           
        }
    }     
}
class Dynamic{
   public void display(){
        System.out.println("Inside Dynamic Class");
    }
   public void display(String name){
        System.out.println("Inside Dynamic Class"+name);
    }
}

output:
Dynamic Loading
Inside Dynamic Class
Inside Dynamic Class Aravind

No comments:

Post a Comment