Create an object from a stringTag(s): Language

In this HowTo, we instantiate an object from its classname and pass a parameter to the constructor. And then, we are calling a method dynamically.
public class Test {
    public static void main(String args[]) {

        try {
          String name = "java.lang.String";
          String methodName = "toLowerCase";

          // get String Class
          Class cl = Class.forName(name);

          // get the constructor with one parameter
          java.lang.reflect.Constructor constructor =
               (new Class[] {String.class});

          // create an instance
          Object invoker =
               (new Object[]{"REAL'S HOWTO"});

          // the method has no argument
          Class  arguments[] = new Class[] { };

          // get the method
          java.lang.reflect.Method objMethod =
             cl.getMethod(methodName, arguments);

          // convert "REAL'S HOWTO" to "real's howto"
          Object result =
               (invoker, (Object[])arguments);

        catch (Exception e) {

blog comments powered by Disqus