views:

193

answers:

3

Is it possible to call a method by reflection from a class?

class MyObject {
    ...   //some methods

    public void fce() {
        //call another method of this object via reflection?
    }
}

Thank you.

+7  A: 

Absolutely:

import java.lang.reflect.*;

public class Test
{
    public static void main(String args[]) throws Exception
    {
        Test test = new Test();
        Method method = Test.class.getMethod("sayHello");
        method.invoke(test);
    }

    public void sayHello()
    {
        System.out.println("Hello!");
    }
}

If you have problems, post a specific question (preferrably with a short but complete program demonstrating the problem) and we'll try to sort it out.

Jon Skeet
Don't create the empty Object array. Take advantage of the varargs signature: invoke(test)
erickson
Will edit in a second - although of course it'll do the same thing.
Jon Skeet
+3  A: 

You can.. But there's are probably better ways to do what you're after (?). To call a method via reflection you could do something like -

class Test {

    public void foo() {
        // do something...
    }

    public void bar() {
        Method method = getClass.getMethod("foo");
        method.invoke(this);
    }
}

If the method you want to invoke has arguments then it's slightly different - you need to pass arguments to the invoke method in addition to the object to invoke it on, and when you get the method from the Class you need to specify a list of argument types. i.e. String.class etc.

Max Stewart
+3  A: 
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


public class Main
{
    public static void main(final String[] argv)
    {
        final Main main;

        main = new Main();
        main.foo();
    }

    public void foo()
    {
        final Class clazz;
        final Method method;

        clazz = Main.class;

        try
        {
            method = clazz.getDeclaredMethod("bar", String.class);
            method.invoke(this, "foo");
        }
        catch(final NoSuchMethodException ex)
        {
            // handle it however you want
            ex.printStackTrace();
        }
        catch(final IllegalAccessException ex)
        {
            // handle it however you want
            ex.printStackTrace();
        }
        catch(final InvocationTargetException ex)
        {
            // handle it however you want
            ex.printStackTrace();
        }
    }

    private void bar(final String msg)
    {
        System.out.println("hello from: " + msg);
    }
}
TofuBeer