google / auto

A collection of source code generators for Java.
Apache License 2.0
10.42k stars 1.2k forks source link

Add support for Kotlin Objects as services for autoService #785

Open ColinHebert opened 4 years ago

ColinHebert commented 4 years ago

Kotlin has a nice singleton system thanks to kotlin objects, it creates a class that works automatically as a singleton, which from the perspective of Java looks like a class with a static field INSTANCE which contains the only instance of the class.

This is particularly helpful in the context of service loaders as it gives more control over the instance used as a service.

Unfortunately, the way ServiceLoader works currently requires classes that can be instantiated using their default constructor, which objects do not have.

But thanks to the magic of annotation processing this is actually fixable. Without any processing this is what someone could write to make "their object" work with ServiceLoader:

interface MyInterface {
    fun myMethod() : String
}

object MyObject : MyInterface {
    override fun myMethod() : String = "hello"
}

@AutoService(MyInterface::class)
class MyObjectServiceLoaderProxy : MyInterface by MyObject

This uses the delegation mechanism also provided in Kotlin; in short, if you are implementing an interface, using by anImplementationOfSaidInterface, instances of the class will delegate the non-explicitely implemented functions to anImplementationOfSaidInterface. Note, this does not work with abstract classes, too bad but not the end of the world.

There, now we can use ServiceLoader "with objects", we just need to tidy it up a bit, having the annotation on the object and generating the class automatically should be doable and would provide all the benefits without requiring user intervention (as long as the "service" is represented by an interface). We can also give a non standard name to the class to avoid people using it by mistake, after all this is only meant to be for the eyes of the ServiceLoader.

Thoughts?

kluever commented 4 years ago

/cc @lowasser

lowasser commented 4 years ago

Seems logical, plausible, and doable. I approve, and have a sketch of an implementation, but adapting the tests might be more difficult.

sschuberth commented 2 years ago

I approve, and have a sketch of an implementation

Any update on that?

tinder-cesardiez commented 2 years ago

This works for me on AutoService 1.0.1