javaandroidmethodsoverriding

How Can I Override Library Methods in Java?


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?


Solution

  • 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.

    UPDATE (april 4, 2024)

    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.