How do I call a method using reflection?
Author: Deron Eriksson
Description: This Java tutorial describes how to use invoke a method using reflection.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.4

Page: < 1 2

(Continued from page 1)

If we execute ClassMethodTest, we see the following result in the console:

getString1 returned: val1
calling setString1 with 'val2'
getString1 returned: val2

As you can see, the Method class's invoke method allowed us to successfully call the getString1() and setString1() methods.

You can only call a Class object's getMethod() on public methods. If you try to call getMethod using a private or protected method, like:

Method gs1Method = tClass.getMethod("getProtectedDude", new Class[] {});

You will receive a 'NoSuchMethodException' like the following:

Exception in thread "main" java.lang.NoSuchMethodException: test.Testing.getProtectedDude()
	at java.lang.Class.getMethod(
	at test.ClassMethodTest.main(

Another thing to note is that if you call a invoke() on a static method, the first parameter of the invoke() call should be null since we are invoking the call on the class, not on a particular object of the class.

Page: < 1 2