0

I want to call a method using reflection.

The method is:

public String format(String text,int value)
{
    return text+" "+value; 
} 

So, it has 2 arguments: a String and an int. And it returns a String. How can I call it?

5
  • Well, how far have you got so far? Have you managed to find the method using reflection? Have you tried invoking it? What happened? Commented Mar 3, 2015 at 13:04
  • I tried to do something but I have a problem to continue public String format(String text,int value){ return text+" "+value; } Commented Mar 3, 2015 at 13:04
  • 2
    Well put what you've got so far into your question, and tell us where you're stuck. Read docs.oracle.com/javase/tutorial/reflect/member/… or a similar tutorial if you're stuck right at the very start. Commented Mar 3, 2015 at 13:06
  • yes, now i can say good with this url docs.oracle.com/javase/tutorial/reflect/member/… , thank you Commented Mar 5, 2015 at 16:26
  • Fixed title. Added the method from the comments. Commented Mar 6, 2015 at 8:58

1 Answer 1

1
    try {
        Class<?> type = Foo.class;
        Method method = type.getMethod("format", String.class, int.class);
        //as the method is not static, you need to have an instance of the class to be able to invoke the method
        Foo instance = new Foo();
        String string = (String) method.invoke(instance, "string", 42);
    } catch (Exception toBeHandled) {}

and replace the Foo with the name of your class

Sign up to request clarification or add additional context in comments.

1 Comment

@aaron-digulla , nope you need an instance of the class to invoke a method as it's not static. That's why I had created an instance of the class

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.