I want to reuse a piece of code written in Private method of another class A. Like
class A
{
private String method(String data){
return "abcd";
}
}
List myList= getListFromSomeSource();
myList.stream()
.map(A::method)
.collect()....etc
I want to reuse a piece of code written in Private method of another class A. Like
class A
{
private String method(String data){
return "abcd";
}
}
List myList= getListFromSomeSource();
myList.stream()
.map(A::method)
.collect()....etc
The only way to access a private
method of a class, if the class implementation does not provide such an option and if that implementation cannot be modified, is via reflection.
Assuming that the method
function of class A
has a String
return type, a simple way to do so is
public static String invokeMethod(A object, String data) throws Exception {
Method method = A.class.getDeclaredMethod(“method”, String.class);
method.setAccessible(true);
return (String) method.invoke(object, data);
}
Since the Class A
method in question is not static, an object reference would need to be used to access it, with or without reflection, e.g.
A object = new A(); // Create object of type A
String data = “...”; // Specify data input
String result = invokeMethod(object, data); // Call method
If such an object of type A
cannot be created, or if the caller does not want to pass to invokeMethod
a reference to such an object, the only other option left is actually rewriting the method
function, outside Class A
.