1Z0-819 · Question #44
Which code fragment does a service use to load the service provider with a Print interface?
The correct answer is B. private Print print=java.util.ServiceLoader<Print>.serviceLoader.load(Print.class). Option B is correct because Java's service-loading mechanism relies on java.util.ServiceLoader and its static load() method, which scans the classpath for registered implementations of a given interface - in this case, Print.class - without the caller needing to know the…
Question
Options
- Aprivate Print print = com.service.Provider.getInstance();
- Bprivate Print print=java.util.ServiceLoader<Print>.serviceLoader.load(Print.class);
- Cprivate java.util.ServiceLoader<Print> loader = new java.util.ServiceLoader<>();
- Dprivate Print print = new com.service.Provider.Printing();
How the community answered
(15 responses)- B80% (12)
- C13% (2)
- D7% (1)
Explanation
Option B is correct because Java's service-loading mechanism relies on java.util.ServiceLoader and its static load() method, which scans the classpath for registered implementations of a given interface - in this case, Print.class - without the caller needing to know the concrete implementing class.
Option A is wrong because com.service.Provider.getInstance() follows the Singleton pattern, not the SPI (Service Provider Interface) pattern; it hard-codes a specific provider rather than dynamically discovering one. Option C is wrong because ServiceLoader cannot be instantiated with new - it is accessed via the static ServiceLoader.load() factory method, making the constructor call invalid. Option D is wrong because new com.service.Provider.Printing() directly instantiates a concrete class, which defeats the purpose of service loading and tightly couples the code to a specific implementation.
Memory tip: ServiceLoader is always about dynamic discovery at runtime. If you see new or a hardcoded class name being constructed, it cannot be a service loader pattern - the whole point of ServiceLoader.load(SomeInterface.class) is that you never name the concrete class yourself.
Topics
Community Discussion
No community discussion yet for this question.