1

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
lotor
  • 1,060
  • 7
  • 18
  • 4
    You can't use a private method outside of the class it is defined in. https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html – jrook Oct 15 '19 at 01:03
  • 4
    You can do it with [reflection](https://stackoverflow.com/a/11282279/2928853). But it is generally a very bad idea to do so. – jrook Oct 15 '19 at 01:06
  • 1
    Can you modify anything or add stuff in class A? – Josh W. Oct 15 '19 at 01:08
  • Yes: why is class `A`' being so secretive? Couldn't `method` be `public` instead of `private`? Is it really doing anything so intensely private that it can't be shared with the rest of the world? – Kevin Anderson Oct 15 '19 at 01:21
  • @Jrook I am not looking for something like your link. I dont want to create the object, just want to refer the method. I cant modify class A. - Its in a library. I dont want to rewrite the logic in that method. Just looking for a way to reuse it. – user3867229 Oct 15 '19 at 01:26
  • I guess you have no way. I don't see any problems when we re-write that method. – Tea Oct 15 '19 at 08:29
  • @TeaNG I did re-write the method for now. I am looking for a way to reuse the existing method. – user3867229 Oct 15 '19 at 13:08
  • The way you describe it, indeed there doesn’t seem to be any other option than rewriting. – PNS Oct 15 '19 at 18:13

1 Answers1

1

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.

PNS
  • 19,295
  • 32
  • 96
  • 143