How do I call a declared 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)

The execution of ClassMethodTest is shown below.

getting declared method 'setProtectedDude'
invoking setProtectedDude with 'blah'

getting declared method 'getProtectedDude'
invoking getProtectedDude
getProtectedDude returned: blah

trying to get method 'getProtectedDude' (will throw exception)
java.lang.NoSuchMethodException: test.Testing.getProtectedDude()
	at java.lang.Class.getMethod(
	at test.ClassMethodTest.main(

As you can see, we can get declared methods (public, protected, or private) using the getDeclaredMethod() method. However, if we try to call getMethod() on a private or protected method, a NoSuchMethodException exception is thrown. After we obtain a Method object via getMethod() or getDeclaredMethod(), we can invoke the method by calling the invoke() method on the Method object.

Page: < 1 2