I have a requirement in which I have to invoke a private method of an abstract class.
Let's say the abstract class looks like below:-
public abstract class Base {
protected abstract String getName();
private String getHi(String v) {
return "Hi " + v;
}
}
Can some let me know is there a way I can call getHi
(may be via Reflection
or some other means) so that I can test it out? I am using Junit 4.12
and Java 8
I have gone through this question but here the methods are not private in the abstract class.
I have also gone through this question even this one does not talk about private method in abstract class.
I am not asking here whether we should test the private method or not or what is the best strategy for testing private methods. There are lot of resources available in the web regarding this. I am just trying to ask how should we invoke a private method of an abstract class in java.
Abstract classes can have private methods. Interfaces can't. Abstract classes can have instance variables (these are inherited by child classes).
Private methods are not inherited, and so cannot be called. If you really want to have access to this method, change its access modifier keyword ( protected or public ). +1 you can only call private methods for classes in the same Java file with the same outer class. Otherwise private means only this class.
To access the abstract class, it must be inherited from another class. Let's convert the Animal class we used in the Polymorphism chapter to an abstract class: Remember from the Inheritance chapter that we use the extends keyword to inherit from a class.
We can call the private method of a class from another class in Java (which are defined using the private access modifier in Java). We can do this by changing the runtime behavior of the class by using some predefined methods of Java. For accessing private method of different class we will use Reflection API.
I am able to invoke the private method of an abstract class as follows:-
Let's say I have a class extending the Abstract base class:-
public class Child extends Base {
protected String getName() {
return "Hello World";
}
}
Then I am able to invoke the private method as below:-
Child child = new Child();
try {
Method method = Base.class.getDeclaredMethod("getHi", String.class);
method.setAccessible(true);
String output = (String) method.invoke(child, "Tuk");
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With