How do I list the public methods of a class?
Author: Deron Eriksson
Description: This Java tutorial describes how to use the Class object's getMethods() method.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.4


Page:    1 2 >

In another tutorial, we saw that we can see the declared methods (public, protected, and private) of a class by calling the getDeclaredMethods() method of a Class object. If you would like to see the public methods of a class (including the public methods that the class inherits), you can do so by calling the getMethods() method of the Class object.

The ClassMethodTest class below demonstrates this. It creates a 'Testing' object, obtains its class, and then gets the public methods of this class via the call to getMethods(), which returns an array of Method objects representing each public method on the class. It then iterates over this array and displays the method signatures.

ClassMethodTest.java

package test;

import java.io.IOException;
import java.lang.reflect.Method;

public class ClassMethodTest {

	public static void main(String args[]) throws IOException {

		Testing t = new Testing("val1", false);

		Class tClass = t.getClass();
		Method[] methods = tClass.getMethods();
		for (int i = 0; i < methods.length; i++) {
			System.out.println("public method: " + methods[i]);
		}
	}
}

The Testing class is shown below.

Testing.java

package test;

public class Testing {

	private String string1;
	private boolean boolean1;
	private String privateDude;
	private String protectedDude;

	public Testing() {
	}

	public Testing(String string1, boolean boolean1) {
		this.string1 = string1;
		this.boolean1 = boolean1;
	}

	private String getPrivateDude() {
		return privateDude;
	}

	private void setPrivateDude(String privateDude) {
		this.privateDude = privateDude;
	}

	protected String getProtectedDude() {
		return protectedDude;
	}

	protected void setProtectedDude(String protectedDude) {
		this.protectedDude = protectedDude;
	}

	public boolean isBoolean1() {
		return boolean1;
	}

	public void setBoolean1(boolean boolean1) {
		this.boolean1 = boolean1;
	}

	public String getString1() {
		return string1;
	}

	public void setString1(String string1) {
		this.string1 = string1;
	}

}

(Continued on page 2)

Page:    1 2 >