Does the scala reflection API (2.10) provide any easier means of searching the loaded classes and filtering the list to specific classes which implement a defined trait? ie;
trait Widget {
def turn(): Int
}
class Cog extends Widget {
def turn() = {
5
}
}
class Sprocket extends Widget {
def turn() = {
10
}
}
I want to search the class library for anything that extends Widget and instantiate those classes. So I would end up with an instance of Cog
and Sprocket
.
I've done similar in Java iterating through the class directories, forming class names and using Class.forName to load a Class object to then check. I'm just wondering if the scala reflection API gives any easier way to search. All examples I've seen thus far have always started from a known class being instantiated, and not from searching over available classes.
This is what
ServiceLoader
is for.I think the reflection API does make it easier to sort out what you need (i.e., for filtering but not for querying the class loader).
If, by your phrase, "searching the loaded classes", you really mean classes that are already loaded, see this question for getting them.
You could imagine a widgets library with an initializer that just ensures that all the widget classes it knows about are loaded. Then the client only needs to know the initializer.
The type test is the same.
Where you're looking for something with type parameters:
Sample:
In case it's been ten years since you used
ServiceLoader
, and who doesn't need a refresher:Stuff:
Comparing Scala and Java. I was going to get a sense of how many LOC to
getGenericInterfaces
and find what you want in Scala, but then I put an end to the exercise.