Invoking Private Methods in Java

06 May 2023 Balmiki Mandal 0 Core Java

Invoking a Private Method in Java

In Java, private methods are prevented from being accessed by external code, which can be beneficial for encapsulation. But at times, it can be useful to be able to invoke private methods in order to unit test them or access hidden functionality of a class. The following article will explain how to invoke a private method in Java.

Using Reflection

The most common and recommended way to invoke a private method in Java is by using reflection. Reflection is a feature of the Java language that allows us to manipulate classes and their members at runtime. With reflection, we can access private methods, fields, and constructors, and invoke them.

To invoke a private method using reflection, we will first need to obtain an instance of the class containing the private method. Then, we can get the Method object from the Class object by calling the getDeclaredMethod() method. We can then call the setAccessible() method on the Method object to bypass the access control checks, and invoke the method by calling the invoke() method on the Method object.

Using Mockito

Mockito is a popular library for unit testing in Java. It provides various features, such as mocking and spying, to facilitate testing of code without the need to modify code or deploy it in real situations.

Mockito provides a feature that allows us to invoke private methods. This is beneficial in cases where the method is not accessible via the public API but needs to be tested. To do this, we can use the invoke() method and pass in the instance of the class and the name of the private method as parameters. Mockito will then take care of invoking the private method for us.

Conclusion

As demonstrated, private methods can be invoked in Java using either reflection or Mockito. Reflection should be used when there is a need to access the private members of a class, while Mockito can be used to invoke private methods and test them without any code modifications.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.