How to Get All Instance and Class Methods In Java

  • Post last modified:December 30, 2023
  • Reading time:2 mins read

Using Reflection to get instance and class methods in Java

Introduction

  • Getting the instance or class methods can be helpful in several use cases, for example documenting API, finding all the methods with a particular annotation for metadata processing, and dynamically invoking methods based on input args.
  • Java reflection provides the feature to read, and modify the class behavior at runtime, and it’s very useful in getting all the methods of a class.

Getting Instance Methods

  • Let’s first create a demo class that has a couple of instance methods.
class DemoClass {

    public void method1(){};

    public void method2(){};

    public void method3(){};
}
  • We are using reflection to get all the declared methods inside the class. getDeclaredMethods() function precisely returns that.
  • We are also filtering any synthetic methods that may be generated by the source code generator and we are filtering static methods out of it.

Getting Class Methods 

  • Let’s add some class methods to our demo class (i.e. static methods in java).
class DemoClass {

    public void method1(){};

    public void method2(){};

    public void method3(){};

    public static void staticMethod1(){};

    public static void staticMethod2(){};
}
  • We can use the same getDeclaredMethods() method to get all the methods defined in the demo class.
  • Now we can filter all the non-synthetic methods with modifiers as static.

Getting Inherited Methods

  • Let’s add the parent class to the demo class.
class AnotherDemoClass {
    public void anotherMethod(){};
}

class DemoClass extends AnotherDemoClass {

    public void method1(){};

    public void method2(){};

    public void method3(){};

    public static void staticMethod1(){};

    public static void staticMethod2(){};
}
  • We can get inherited methods using getMethods() and filter all the synthetic methods.

Source Code

  • Find all the source code used in this article here.

Conclusion

  • In this article, we discussed the use cases of getting class and instance methods. We also coded and wrote the test cases to verify it.

Before You Leave

Leave a Reply