[ Back | Previous | Next ]

How to invoke a java.lang.reflect.Method?

Package:
java.lang.reflect.*
Product:
JDK
Release:
1.1.x
Related Links:
General
Field
Method
Comment:
Let's say we have a storage object with multiple vars and we want to perform an isEmpty test on them but we are too lazy to type the methods for all vars.

We can use the java.lang.reflect package to invoke a method on a class.
package test;

import java.lang.reflect.*;


public class ReflectTest
{
    public static void main(String[] argv)
    {
        String _func_name = argv[0];
        ReflectTest _reflect_test = new ReflectTest();
        _reflect_test.callIt(_func_name);
    }

    public ReflectTest()
    {
    }

    public void callIt(String func_name)
    {
        try
        {
            Class _class = getClass();
            Method _func_to_call = _class.getMethod(func_name, null);
       _func_to_call.invoke(this, null);
        }
        catch ( Exception _e )
        {
            System.out.println("Failed to invoke function " + _e);
        }
    }

    public void hello()
    {
        System.out.println("Hello called");
    }
}