2

I'm working on a large Android project which is using Gson. The method fromJson() is called dozens of times in many files. I need to provide some special-case tests every time this method is called.

Rather than going through and repeating the tests for each and every time this method is used, I'd like to follow the DRY doctrine and simply override the fromJson() method somehow.

My first thought is to make a child class of Gson and override the method, but I would still have to make dozens (perhaps hundreds) of changes to make this work. But even if I were willing to do this work, Gson is final and thus can't be extended.

Second thought: it might be possible to alter the Gson library code. But I don't want to go this route as I'm afraid that I may break something that otherwise works perfectly.

This is an area of Java that I have never ventured before. Anyone have any suggestions?

SMBiggs
  • 11,034
  • 6
  • 68
  • 83
  • Could you use [Aspectj](https://eclipse.org/aspectj/)? – Patricia Shanahan Jun 04 '15 at 00:15
  • Try Spy from Mockito: http://docs.mockito.googlecode.com/hg/1.9.5/org/mockito/Spy.html - you can override exactly one method, add some logic there, and then call the real method. – user3707125 Jun 04 '15 at 00:17
  • I have used neither Aspectj nor Mockito. I'm reluctant to add yet another library to this project, but I will spend an hour looking into these possibilities. – SMBiggs Jun 04 '15 at 14:33
  • 1
    @ScottBiggs Not sure if reflection for java works the same way as reflection works when compiling using the android SDK. But here is an excellent answer that shows how you can in-fact 'hack' the final field of this library: http://stackoverflow.com/a/3301720 – CausingUnderflowsEverywhere May 05 '17 at 18:40
  • @CausingUnderflowsEverywhere: Very promising. Unfortunately my knowledge of reflection is very limited. – SMBiggs May 24 '17 at 04:20

1 Answers1

2

Since there are no responses, I'm going to go ahead and give my own answer.

If a library class/method is declared final, the whole point is to never inherit or override said class. And since it's a library (and I don't have access to the source), there is no way to change it.

  • Solution #1: Write my own library. Which of course defeats the entire purpose of using libraries (to keep from having to re-invent the wheel).

  • Solution #2: Find a work-around. As hack-y as this sounds, this is probably the most reasonable choice.

  • Solution #3: Live with the bug/error/lack-of-feature. Not all issues are show-stoppers. You might be able to have a great program that still doesn't live up to every desired detail.

  • Solution #4: Abandon the project. Sometimes this may be a viable option. But not for me at this time.

SMBiggs
  • 11,034
  • 6
  • 68
  • 83
  • 2
    If you don't like the solution, feel free to write your own. If it's even half-assed, I'll give it a check. At least write a comment to explain the down-vote! – SMBiggs May 24 '17 at 04:17