//Gets all public methods (including static) from the class and all its parent chain
Method [] methods = MethodCls.class.getMethods();
show(methods);
System.out.println("##############################");
//Gets all methods (including static) declared in the class
//irrespective of the visibility
methods = MethodCls.class.getDeclaredMethods();
show(methods);
System.out.println("##############################");
try {
//We can access only public methods
Method method = MethodCls.class.getMethod("publicMethod");
System.out.println(method);
//Accessing the following methods throws java.lang.NoSuchMethodException
private static void show(Method [] methods) {
System.out.println("Total methods : " + methods.length); for (int i = 0 ; i < methods.length ; i ++) {
System.out.println(methods[i]);
}
}
}
class MethodCls {
void friendlyMethod() {
}
private void privateMethod() {
}
protected void protectedMethod() {
}
public void publicMethod() {
}
static void friendlyStaticMethod() {
}
public static void publicStaticMethod() {
}
}
It gives the following output,
Total methods : 11
public void com.bethecoder.tutorials.reflection.MethodCls.publicMethod()
public static void com.bethecoder.tutorials.reflection.MethodCls.publicStaticMethod()
public final void java.lang.Object.wait() throws java.lang.InterruptedException
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
public native int java.lang.Object.hashCode()
public final native java.lang.Class java.lang.Object.getClass()
public boolean java.lang.Object.equals(java.lang.Object)
public java.lang.String java.lang.Object.toString()
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()
##############################
Total methods : 6
public void com.bethecoder.tutorials.reflection.MethodCls.publicMethod()
void com.bethecoder.tutorials.reflection.MethodCls.friendlyMethod()
private void com.bethecoder.tutorials.reflection.MethodCls.privateMethod()
protected void com.bethecoder.tutorials.reflection.MethodCls.protectedMethod()
static void com.bethecoder.tutorials.reflection.MethodCls.friendlyStaticMethod()
public static void com.bethecoder.tutorials.reflection.MethodCls.publicStaticMethod()
##############################
public void com.bethecoder.tutorials.reflection.MethodCls.publicMethod()