Java Reflection – Method Example

Using Java Reflection you can interrogate any class and find out all the methods that are available to you. When you call the getMethods() method, it will return to you a Method[] array with the objects of methods that have been public in the class. Calling getDeclaredMethods() method, returns a Method[] array with the all the methods that have been declared including private, protected and default(package) access methods.

In this example, I will show you how to use these two methods to get these details.


Getting All Public Methods for a given Class

Class<?> mc = Class.forName(className);
Method[] publicMethods = mc.getMethods();

Calling the getMethods() method will return to you a Method[] array with the objects of methods that have been public in the class.

Iterating through all the Public Methods

for (Method method : publicMethods) {
  int mods = method.getModifiers();
  Annotation[] annotations = method.getAnnotations();
   
  System.out.println("  PUBLIC METHODS are " + method.getName() 
       + " mods=" + Modifier.toString(mods)
       + " retType=" + method.getReturnType()
       + " annotation=" + Arrays.toString(annotations)
      );
}

As you can see from the output below, only PUBLIC methods are being returned by the getMethods() call. I have also added information on the access modifiers, return type and annotations available to us.

Output

Details for com.avaldes.tutorials.Mammal
  PUBLIC METHODS are toString mods=public retType=class java.lang.String annotation=[]
  PUBLIC METHODS are getName mods=public retType=class java.lang.String annotation=[]
  PUBLIC METHODS are setName mods=public retType=void annotation=[]
  PUBLIC METHODS are sleep mods=public retType=void annotation=[]
  PUBLIC METHODS are setHair mods=public retType=void annotation=[]
  PUBLIC METHODS are eat mods=public retType=void annotation=[]
  PUBLIC METHODS are walk mods=public retType=void annotation=[]
  PUBLIC METHODS are getMammalCount mods=public static retType=int annotation=[]
  PUBLIC METHODS are isHair mods=public retType=boolean annotation=[]
  PUBLIC METHODS are wait mods=public final native retType=void annotation=[]
  PUBLIC METHODS are wait mods=public final retType=void annotation=[]
  PUBLIC METHODS are wait mods=public final retType=void annotation=[]
  PUBLIC METHODS are equals mods=public retType=boolean annotation=[]
  PUBLIC METHODS are hashCode mods=public native retType=int annotation=[]
  PUBLIC METHODS are getClass mods=public final native retType=class java.lang.Class annotation=[]
  PUBLIC METHODS are notify mods=public final native retType=void annotation=[]
  PUBLIC METHODS are notifyAll mods=public final native retType=void annotation=[]

Getting All Declared Methods for a given Class

Class<?> mc = Class.forName(className);
Method[] declaredMethods = mc.getDeclaredMethods();

Calling getDeclaredMethods() method returns a Method[] array with the all the methods that have been declared including private, protected and default(package) access methods.

Iterating through all the Declared Methods

for (Method method : declaredMethods) {
  int mods = method.getModifiers();
  Annotation[] annotations = method.getDeclaredAnnotations();
   
  System.out.println("  DECLARED METHODS are " + method.getName() 
       + " mods=" + Modifier.toString(mods)
       + " retType=" + method.getReturnType()
       + " annotation=" + Arrays.toString(annotations)
      );
}

This method is slightly different than the previous one in that it will return PUBLIC, PRIVATE, PROTECTED and DEFAULT or PACKAGE access level methods via the getDeclaredMethods() call. As in the last example, we have information on the access modifiers, return type and annotations available to us.

Output

Details for com.avaldes.tutorials.Mammal
  DECLARED METHODS are toString mods=public retType=class java.lang.String annotation=[]
  DECLARED METHODS are getName mods=public retType=class java.lang.String annotation=[]
  DECLARED METHODS are setName mods=public retType=void annotation=[]
  DECLARED METHODS are sleep mods=public retType=void annotation=[]
  DECLARED METHODS are setHair mods=public retType=void annotation=[]
  DECLARED METHODS are eat mods=public retType=void annotation=[]
  DECLARED METHODS are walk mods=public retType=void annotation=[]
  DECLARED METHODS are incCount mods=private static retType=void annotation=[]
  DECLARED METHODS are getMammalCount mods=public static retType=int annotation=[]
  DECLARED METHODS are privateMethod mods=private retType=void annotation=[]
  DECLARED METHODS are protectedMethod mods=protected retType=void annotation=[]
  DECLARED METHODS are isHair mods=public retType=boolean annotation=[]


Getting Individual Method by Name

Class<?> mc = Class.forName("com.avaldes.tutorials.Dog");
Dog fido = (Dog) mc.newInstance();
Method method = mc.getMethod("setName", new Class[] { String.class });

Getting and Invoking Public Method by Name (having String argument)

Class<?> mc = Class.forName("com.avaldes.tutorials.Dog");
Dog fido = (Dog) mc.newInstance();
    
System.out.println("\nInvoke methods for com.avaldes.tutorials.Dog");

System.out.println("Before ==> " + fido.toString());
    
// Let's invoke setName() method -- it takes a String arg
System.out.println("Setting name to Kayla");
Method method = mc.getMethod("setName", new Class[] { String.class });
method.invoke(fido, "Kayla");

Getting and Invoking Public Method by Name (having boolean argument)

Class<?> mc = Class.forName("com.avaldes.tutorials.Dog");
Dog fido = (Dog) mc.newInstance();
    
// Let's invoke setHair() method -- it takes a boolean arg
System.out.println("Setting hair to true");
Method method = mc.getMethod("setHair", new Class[] { boolean.class });
method.invoke(fido, true);

Getting and Invoking Public Method by Name (with no arguments)

Class<?> mc = Class.forName("com.avaldes.tutorials.Dog");
Dog fido = (Dog) mc.newInstance();
    
// Let's invoke eat() method -- it takes no parameters
System.out.println("Let's eat()");
Method method = mc.getMethod("eat", new Class[] {});
method.invoke(fido);

Getting and Invoking Private Method by Name (with no arguments)

In order to get private, protected or default(package) methods you will need to use the getDeclaredMethod() method instead of the getMethod() we were using previously. In addition, you will need to use the setAccessible() method passing in a flag of true. A value of true indicates that the reflected object should suppress Java language access checking. However if the application has been run with a security manager using a restrictive policy, then calling this method may throw a SecurityException.

Class<?> mc = Class.forName("com.avaldes.tutorials.Dog");
Dog fido = (Dog) mc.newInstance();
    
// Let's invoke private method tellASecret() -- it takes no parameters
System.out.println("Shhhh it's a Secret...");
Method method = mc.getDeclaredMethod("tellASecret");
method.setAccessible(true);
method.invoke(fido);

Full Program Listing (MethodExample.java)

package com.avaldes.tutorials;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;

public class MethodExample {

  public static void ShowDeclaredMethod(String className) 
      throws ClassNotFoundException {
    
    Class<?> mc = Class.forName(className);
    
    System.out.println("\nDetails for " + className);
    Method[] declaredMethods = mc.getDeclaredMethods();
    for (Method method : declaredMethods) {
      int mods = method.getModifiers();
      Annotation[] annotations = method.getDeclaredAnnotations();
      
      System.out.println("  DECLARED METHODS are " + method.getName() 
          + " mods=" + Modifier.toString(mods)
          + " retType=" + method.getReturnType()
          + " annotation=" + Arrays.toString(annotations)
          );
    }
  }
  
  public static void ShowPublicMethod(String className) 
      throws ClassNotFoundException {
    
    Class<?> mc = Class.forName(className);
    
    System.out.println("\nDetails for " + className);
    Method[] publicMethods = mc.getMethods();
    for (Method method : publicMethods) {
      int mods = method.getModifiers();
      Annotation[] annotations = method.getAnnotations();
      
      System.out.println("  PUBLIC METHODS are " + method.getName() 
          + " mods=" + Modifier.toString(mods)
          + " retType=" + method.getReturnType()
          + " annotation=" + Arrays.toString(annotations)
          );
    }
  }

  public static void invokeDogMethods() 
      throws ClassNotFoundException, SecurityException, 
      NoSuchMethodException, InstantiationException, 
      IllegalAccessException, IllegalArgumentException, 
      InvocationTargetException {
    
    Class<?> mc = Class.forName("com.avaldes.tutorials.Dog");
    Dog fido = (Dog) mc.newInstance();
    
    System.out.println("\nInvoke methods for com.avaldes.tutorials.Dog");

    System.out.println("Before ==> " + fido.toString());
    
    // Let's invoke setName() method -- it takes a String arg
    System.out.println("Setting name to Kayla");
    Method method = mc.getMethod("setName", new Class[] { String.class });
    method.invoke(fido, "Kayla");
    
    
    // Let's invoke setHair() method -- it takes a boolean arg
    System.out.println("Setting hair to true");
    method = mc.getMethod("setHair", new Class[] { boolean.class });
    method.invoke(fido, true);

    // Let's invoke eat() method -- it takes no parameters
    method = mc.getMethod("eat", new Class[] {});
    method.invoke(fido);
    
    // Let's invoke private method tellASecret() method -- it takes no parameters
    method = mc.getDeclaredMethod("tellASecret");
    method.setAccessible(true);
    method.invoke(fido);
    
    System.out.println("After ==> " + fido.toString());
  }
  
  public static void main(String[] args) {
    try {
      ShowDeclaredMethod("com.avaldes.tutorials.Animal");
      ShowDeclaredMethod("com.avaldes.tutorials.Mammal");
      ShowPublicMethod("com.avaldes.tutorials.Mammal");
      ShowDeclaredMethod("com.avaldes.tutorials.Bird");
      ShowDeclaredMethod("com.avaldes.tutorials.Dog");
      
      // Invoke some methods from Dog class
      invokeDogMethods();
      
    } catch (Exception e){
      e.printStackTrace();
    }
  }
}

Full Program Listing (Animal.java)

package com.avaldes.tutorials;

public interface Animal {
  public boolean isAwake = false;
  
  public void eat();
  public void sleep();
  void walk();
}

Full Program Listing (Mammal.java)

package com.avaldes.tutorials;

public class Mammal implements Animal {

  private boolean hair = false;
  private String name = null;
  private static int MammalCount = 0; 
  
  public Mammal() {
    incCount();
  }
  
  public String getName() {
    return name;
  }
  
  public static int getMammalCount() {
    return MammalCount;
  }


  private static void incCount() {
    MammalCount++;
  }

  public void setName(String name) {
    this.name = name;
  }

  private void privateMethod() {
    System.out.println("Private Method!!!");
  }
  
  protected void protectedMethod() {
    System.out.println("Protected Method!!!");
  }
  
  @Override
  public void eat() {
    System.out.println("Mammal is eating...");
  }

  @Override
  public void sleep() {
    System.out.println("Mammal is Sleeping...");
  }

  @Override
  public void walk() {
    System.out.println("Mammal is Walking...");
  }

  public boolean isHair() {
    return hair;
  }

  public void setHair(boolean hair) {
    this.hair = hair;
  }

  public String toString() {
    return "[name=" + getName() + ", hair=" + isHair() + ", Mammals=" + getMammalCount() + "]";
  }
}

Full Program Listing (Dog.java)

package com.avaldes.tutorials;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME) 
@interface Detail {
  String description();
}

@Retention(RetentionPolicy.RUNTIME) 
@interface Tag {}

public class Dog extends Mammal implements Animal {
  public Dog() {
  }
  
  public Dog(String name) {
    setName(name); 
  }
  
  public Dog(String name, boolean hair) {
    this.setName(name);
    this.setHair(hair);
  }
  
  @Override
  public void eat() {
    System.out.println("Dog is eating...");
  }

  @Override
  public void sleep() {
    System.out.println("Dog is Sleeping...");
  }

  @Override
  public void walk() {
    System.out.println("Dog is Walking...");
  }
  
  @Tag
  public void Bark() {
    System.out.println("Dog is Barking...");
  }
  
  @Tag
  @Detail(description = "Display private secret message")
  private void tellASecret() {
    System.out.println("All dogs go to Heaven...");
  }
  
  public class PublicInnerClass {}
  private class PrivateInnerClass {}
  protected class ProtectedInnerClass {}
  class DefaultInnerClass {}
}

Full Program Listing (Bird.java)

package com.avaldes.tutorials;

public class Bird implements Animal {
  
  private String name = null; 
  
  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  @Override
  public void eat() {
    System.out.println("Bird is eating...");
  }

  @Override
  public void sleep() {
    System.out.println("Bird is Sleeping...");
  }

  @Override
  public void walk() {
    System.out.println("Bird is Walking...");
  }
  
  public void fly() {
    System.out.println("Bird is Flying...");
  }

  public String toString() {
    return "[name=" + getName() + "]";
  }
}

Output

Details for com.avaldes.tutorials.Animal
  DECLARED METHODS are sleep mods=public abstract retType=void annotation=[]
  DECLARED METHODS are eat mods=public abstract retType=void annotation=[]
  DECLARED METHODS are walk mods=public abstract retType=void annotation=[]

Details for com.avaldes.tutorials.Mammal
  DECLARED METHODS are toString mods=public retType=class java.lang.String annotation=[]
  DECLARED METHODS are getName mods=public retType=class java.lang.String annotation=[]
  DECLARED METHODS are setName mods=public retType=void annotation=[]
  DECLARED METHODS are sleep mods=public retType=void annotation=[]
  DECLARED METHODS are setHair mods=public retType=void annotation=[]
  DECLARED METHODS are eat mods=public retType=void annotation=[]
  DECLARED METHODS are walk mods=public retType=void annotation=[]
  DECLARED METHODS are incCount mods=private static retType=void annotation=[]
  DECLARED METHODS are getMammalCount mods=public static retType=int annotation=[]
  DECLARED METHODS are privateMethod mods=private retType=void annotation=[]
  DECLARED METHODS are protectedMethod mods=protected retType=void annotation=[]
  DECLARED METHODS are isHair mods=public retType=boolean annotation=[]

Details for com.avaldes.tutorials.Mammal
  PUBLIC METHODS are toString mods=public retType=class java.lang.String annotation=[]
  PUBLIC METHODS are getName mods=public retType=class java.lang.String annotation=[]
  PUBLIC METHODS are setName mods=public retType=void annotation=[]
  PUBLIC METHODS are sleep mods=public retType=void annotation=[]
  PUBLIC METHODS are setHair mods=public retType=void annotation=[]
  PUBLIC METHODS are eat mods=public retType=void annotation=[]
  PUBLIC METHODS are walk mods=public retType=void annotation=[]
  PUBLIC METHODS are getMammalCount mods=public static retType=int annotation=[]
  PUBLIC METHODS are isHair mods=public retType=boolean annotation=[]
  PUBLIC METHODS are wait mods=public final native retType=void annotation=[]
  PUBLIC METHODS are wait mods=public final retType=void annotation=[]
  PUBLIC METHODS are wait mods=public final retType=void annotation=[]
  PUBLIC METHODS are equals mods=public retType=boolean annotation=[]
  PUBLIC METHODS are hashCode mods=public native retType=int annotation=[]
  PUBLIC METHODS are getClass mods=public final native retType=class java.lang.Class annotation=[]
  PUBLIC METHODS are notify mods=public final native retType=void annotation=[]
  PUBLIC METHODS are notifyAll mods=public final native retType=void annotation=[]

Details for com.avaldes.tutorials.Bird
  DECLARED METHODS are toString mods=public retType=class java.lang.String annotation=[]
  DECLARED METHODS are getName mods=public retType=class java.lang.String annotation=[]
  DECLARED METHODS are setName mods=public retType=void annotation=[]
  DECLARED METHODS are sleep mods=public retType=void annotation=[]
  DECLARED METHODS are eat mods=public retType=void annotation=[]
  DECLARED METHODS are walk mods=public retType=void annotation=[]
  DECLARED METHODS are fly mods=public retType=void annotation=[]

Details for com.avaldes.tutorials.Dog
  DECLARED METHODS are sleep mods=public retType=void annotation=[]
  DECLARED METHODS are eat mods=public retType=void annotation=[]
  DECLARED METHODS are tellASecret mods=private retType=void annotation=[@com.avaldes.tutorials.Tag(), @com.avaldes.tutorials.Detail(description=Display private secret message)]
  DECLARED METHODS are walk mods=public retType=void annotation=[]
  DECLARED METHODS are Bark mods=public retType=void annotation=[@com.avaldes.tutorials.Tag()]

Invoke methods for com.avaldes.tutorials.Dog
Before ==> [name=null, hair=false, Mammals=1]
Setting name to Kayla
Setting hair to true
Dog is eating...
All dogs go to Heaven...
After ==> [name=Kayla, hair=true, Mammals=1]

Related Reflection Examples

  • Class Example
    Simple example shows you how to dynamically load and instantiate a class, get class name, package name, and superclass name.
  • Modifier Example
    Showing you how to get information about classes, fields and methods using modifier method.
  • Method Example
    Providing full details of how to get all methods, and invoke methods using reflection.

Please Share Us on Social Media

Facebooktwitterredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *