I need to call a method that is available in a third party library, but it is a private method. There is no direct or indirect way to obtain the same functionality via public methods available.

I could do this in at least two ways:

  • Copy paste the class into my source code tree (the license permits) and change the method declaration to accessible.
  • Use Java reflection to call the private method.
  • Ok I can also open pull request to change the visibility on the third party library community side (I did), but they may accept, may not, unclear how long would it take, and I need the functionality provided by this method.

Both approaches do not look very nice. Which one is less ugly?

  • Is it not possible to copy only the private method? – Esben Skov Pedersen Feb 7 '18 at 20:12
  • No, two classes are the smallest amount of code that could be copied. – h22 Feb 8 '18 at 7:56

If the functionality is not part of the library's API, you shouldn't use it. There's no guarantee it will still be available in future versions, and that it won't change. So using reflection to access the internals is a strategy of last resort.

It is often sensible to fork the library and add this functionality yourself. You can then offer a pull request to the upstream project, so that your changes may be part of a future mainstream release. This strategy is preferable because your change will be supported by the upstream project. But this only works if your change fits into the vision of the project, e.g. no drastic expansion of scope. Just changing a method from private to public is likely not an acceptable change. That's a hack. Instead, evaluate how the library should be designed in order to address your use case.

If the upstream project will not accept your suggestion, you can still maintain your fork. However, this makes it difficult to keep up to date with updates. This is especially problematic for security updates. Over time, merging upstream with your changes will become more and more difficult as they diverge. Please consider whether you can commit to the maintenance of this fork, and therefore carry this risk.

For changes that are only useful to you, provide that functionality as a completely separate class or library. If the original library is licensed appropriately, you can reuse relevant parts of the source code. Simply copying a whole class and changing some details is not likely to be helpful. Instead, view this source code as a starting point for your own design.

  • 1
    Hack, not hack, the required functionality is missing. Accepting the suggestion to for the library. – h22 Feb 7 '18 at 9:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.