how to check if a service implements an interface in grails

234 views Asked by At

I have an interface "TestInterface" and grails service "TestService" that implements the "TestInterface". But when I test if I have a service that implements the interface like this:

application.serviceClasses?.each { serviceClazz ->

            if(serviceClazz instanceof TestInterface) {
                println "service name => "+ serviceClazz.name;
            }
}

The result is I am not getting anything neither error nor my expectation ( service name => TestService )

I have also tried changing the serviceClazz to serviceClazz.class,serviceClazz.metaClass in the if condition but still not working.

Thank you,

1

There are 1 answers

4
Marcin Świerczyński On BEST ANSWER

What about:

if (TestInterface.class.isAssignableFrom(serviceClazz)) {
    ... 
}

UPDATE

So I managed to run the actual example using Grails 2.3.11.

class BootStrap {

    def grailsApplication

    def init = { servletContext ->
        grailsApplication.serviceClasses.each { serviceClazz ->
            if (TestInterface.isAssignableFrom(serviceClazz.clazz)) {
                println serviceClazz
            }
        }
    }
    def destroy = {
    }
}

As you can see, the important part is clazz in serviceClazz.clazz.

Hope this helps!