Tuesday, October 11, 2011

Instantiate unknown class at runtime and call the object's methods


This java code example shows how to create an object at runtime for which the name of the class is not know at compile time.We use the forName() method to load the class and then use the newInstance() method to create the object. Then we use reflection to get the methods of the class and invoke them. The class we are instantiating is called MyClass (see further below) and we assume that the methods we are interested in starts with the string 'say' (we don't want to call all the methods inherited from java.lang.Object).

package org.best.example;

import java.lang.reflect.Method;


public class Main {

    public void loadClass() {
        try {

            Class myclass = Class.forName(getClassName());

            //Use reflection to list methods and invoke them
            Method[] methods = myclass.getMethods();
            Object object = myclass.newInstance();
           
            for (int i = 0; i < methods.length; i++) {
                if (methods[i].getName().startsWith("say")) {
                    System.out.println(methods[i].invoke(object));
                }
               
            }
           
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
   
    private String getClassName() {
       
        //Do appropriate stuff here to find out the classname
       
        return "
org.best.example.MyClass";
    }

    public static void main(String[] args) {
        new Main().loadClass();
    }
}

MyClass:

package org.best.example;


public class MyClass {
   
    public String sayHello() {
       
        return "Hello";
    }
   
    public String sayGoodbye() {
       
        return "Goodbye";
    }

}


The output from the example will be:
Hello
Goodbye

No comments: