Issue #ServiceLoaderEnhancement
Stephen Colebourne
scolebourne at joda.org
Fri Jul 1 09:27:39 UTC 2016
The ServiceLoader API is to be pushed as a key class by the module
system. This issue is proposing enhancements to the API. Others may
want to add their own proposals.
Currently, ServiceLoader requires service implementations to have a
public no-args constructor on a public class. This is very
restrictive, especially in a Java 8 world of immutable classes and
factory methods (with constructors actively avoided).
JSR-310 has a service for loading Chronology implementations. In
ThreeTen-Extra, I have a number of additional implementations [1].
Unfortunately, all the implementations are forced to have a public
no-args constructor, as ServiceLoader cannot make use of the singleton
INSTANCE constant. As can be seen, I have to mark the public no-args
constructor as deprecated [2]. This state of affairs is frankly
ridiculous, and is one of the reasons putting me off using
ServiceLoader non-JDK code.
I propose that the spec of ServiceLoader is extended to make it more useful.
Firstly, I propose that all reflection by ServiceLoader should use
setAccessible(true) to allow providers to be non-public.
Secondly, I propose that if no public no-args constructor is found on
the provider class, ServiceLoader should locate a public static
constant named "INSTANCE" and use that instead.
This proposal could be extended further. Instead of searching for
"INSTANCE", it could look for all public static constants of the
provider type, allowing one provider class to result in many provider
instances.
Thirdly, it should be possible to access the set of provider classes
without instantiating them. This would allow applications to use the
module-info design for services without using ServiceLoader, eg to
reflect on the provider classes, perhaps to search for annotations.
I hope this proposal is given serious consideration, as at present the
design of ServiceLoader is simply too restrictive to be appropriate to
be hard coded into the module specification.
Stephen
[1] https://github.com/ThreeTen/threeten-extra/tree/master/src/main/java/org/threeten/extra/chrono
[2] https://github.com/ThreeTen/threeten-extra/blob/master/src/main/java/org/threeten/extra/chrono/CopticChronology.java#L71
More information about the jpms-spec-observers
mailing list