How do I list the declared methods of a class?
Author: Deron Eriksson
Description: This Java tutorial describes how to use the Class object's getDeclaredMethods() method.
Tutorial created using:
Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.4
If you have an object, you can get its Class object by calling getClass() on the object. If you'd like to list the public, protected, and private methods that the class declares, you can do so by calling the getDeclaredMethods() method of the class object, which returns an array of Method objects representing the methods that are declared by the class. The ClassMethodTest class below illustrates this. ClassMethodTest.javapackage 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.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { System.out.println("method: " + methods[i]); } } } The ClassMethodTest class creates a 'Testing' object, which is shown here. Testing.javapackage 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) Related Tutorials:
|