Search code examples
javaclasscastexceptionjmfservice-provider

ServiceRegistry constructor fails with ClassCastException on concrete class


Trying to use javax.imageio.spi.ServiceRegistry to dynamically register request processors for an HttpServlet:

    private static final Class PROVIDER_CLASS = IRequestProcessor.class;

 private void loadProviders() throws ClassNotFoundException {
  _serviceRegistry = new ServiceRegistry(ServiceRegistry.lookupProviders(PROVIDER_CLASS));
 }

The error I get is:

 java.lang.ClassCastException: org.confused.servlet.GetStandardCodesProcessor
javax.imageio.spi.ServiceRegistry.<init>(ServiceRegistry.java:103
org.confused.servlet.MyServlet.loadProviders(.java:100)
 org.confused.servlet.MyServlet.checkProviders(.java:106)
 org.confused.servlet.MyServlet.service(.java:44)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

The class GetStandardCodesProcessor implements IRequestProcessor. The call ServiceRegistry.lookupProviders() is getting a list of classes from the file META-INF/services/org.confused.servlet.IRequestProcessor. It seems I am missing a nuance about how to pass in the iterator from ServiceRegistry.lookupProviders().

This page shows pretty much what I'm doing, albeit assigning the the return from lookupProviders() to an untyped Iterator, which in turn gets passed to the ServiceRegistry constructor. That technique gives the same error for me.

Lastly, I am running this in Eclipse Gallileo (build 20100218-1602), if that matters.

Regards, Drew


Solution

  • I have never used this SPI class before, however, from the API documentation, the constructor of ServiceRegistry takes in an Iterator with categories, not providers. You may want to register your providers with registerServiceProviders() instead?