Search code examples
androidretrofit2android-room

Interface in Room and Retrofit


When using the retrofit library, you create an interface that contains functions with all your endpoints but you never implement it anywhere. My question is where is this interface implemented? I have noticed the same pattern when creating a DAO when using android Room


Solution

  • They use two different approaches, Retrofit takes advantage of Java reflection proxy which is a tool to implement interfaces in runtime, your proxy's invoke method will retrieve the called method scheme through reflection and can work based on that. In fact retrofit can work with method metadata only.

    Proxy is a way to create objects from interfaces without implementing them using code, but by a single invoke method which simply gets these arguments

    @Override
        public Object invoke(Object proxy, Method method, Object[] args) 
          throws Throwable {
            Log.d("proxyCall", method.getName());
    
            return Response (...);
        }
    

    You can get other info from method as well (like it's annotations e.g. @GET etc.)

    On the other hand, Room uses annotation processors to generate code during compile time (you add it's processor a.k.a. compiler in the gradle configuration using annotationProcessor or kapt). You can find the Room's generated source codes inside the build folder of your module.