Reputation: 11688
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?
Upvotes: 3
Views: 4609
Reputation: 11688
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.
This is actually what we did (many months later). We encapsulated the Gson library within our own class, let's call it MyGson. Inside this class is a Gson object. It's used to do the actual Gson calls. This allows us to do special things before and after the regular Gson calls.
Here is some pseudo-code:
public class MyGson {
private Gson gson = new Gson();
public void fromJson() {
// do my necessary stuff
return gson.fromJson()
}
}
The only caveat is that you need to make sure that ONLY THIS CLASS access the Gson library. As long as you stick to this practice, you can do all sorts of things with libraries and their private methods.
Upvotes: 3