简体   繁体   中英

How can I find all implementations of interface in classpath in groovy project?

I'm implementing an interface and now I'd like to get all implementations of this interface in classpath. Is this possible or should I do something else?

You can use the Reflections library for this sort of thing, ie; to find all classes in org.codehaus.groovy which implement the Iterator interface, you can do:

@Grab( 'org.slf4j:slf4j-api:1.7.5' )
@Grab( 'org.reflections:reflections:0.9.9-RC1' )
import org.reflections.*

new Reflections( 'org.codehaus.groovy' ).getSubTypesOf( Iterator ).each {
    println it.name
}

Which prints:

org.codehaus.groovy.runtime.StringGroovyMethods$1
org.codehaus.groovy.runtime.SwingGroovyMethods$7
org.codehaus.groovy.util.ArrayIterator
org.codehaus.groovy.runtime.metaclass.ConcurrentReaderHashMap$KeyIterator
org.codehaus.groovy.control.CompilationUnit$9
org.codehaus.groovy.runtime.SqlGroovyMethods$ResultSetMetaDataIterator
org.codehaus.groovy.runtime.SwingGroovyMethods$1
org.codehaus.groovy.util.ManagedLinkedList$Iter
org.codehaus.groovy.runtime.SwingGroovyMethods$3
org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl$2
org.codehaus.groovy.runtime.SwingGroovyMethods$6
org.codehaus.groovy.ant.FileIterator
org.codehaus.groovy.runtime.IOGroovyMethods$3
org.codehaus.groovy.runtime.DefaultGroovyMethods$DropWhileIterator
org.codehaus.groovy.runtime.DefaultGroovyMethods$TakeIterator
org.codehaus.groovy.runtime.DefaultGroovyMethods$3
org.codehaus.groovy.runtime.SwingGroovyMethods$5
org.codehaus.groovy.runtime.SwingGroovyMethods$2
org.codehaus.groovy.runtime.metaclass.ConcurrentReaderHashMap$HashIterator
org.codehaus.groovy.runtime.metaclass.ConcurrentReaderHashMap$ValueIterator
org.codehaus.groovy.runtime.XmlGroovyMethods$1
org.codehaus.groovy.runtime.SwingGroovyMethods$4
org.codehaus.groovy.runtime.IOGroovyMethods$2
org.codehaus.groovy.runtime.ReverseListIterator
org.codehaus.groovy.runtime.DefaultGroovyMethods$TakeWhileIterator

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM