Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a method using reflection

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.

like image 667
michal Avatar asked Dec 14 '22 05:12

michal


1 Answers

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.

like image 82
Jon Skeet Avatar answered Dec 24 '22 11:12

Jon Skeet