Reputation: 120513
Is there a way I can "loop through" the set of classes in a specified package in Scala?
The use case is managing a set of services inheriting from a BaseService trait that get exposed by a provided name to a REST API. A Manager class needs to be able to provide a list of services as well as validate that a provided service exists, and, if so, instantiate it an execute an overloaded function.
My thought is something like this pseudocode:
for ( clazz <- com.demo.pkg ) {
val service = Class.forName(clazz).newInstance
registerService( service )
}
Rather than instantiation, static methods on a same-named object to provide service name and description may be better.
In Python, this is trivial because of dir() and in PHP is fairly easy due to the classloader functions but I am new to Scala.
Also, I understand I may be approaching this incorrectly and would welcome feedback.
Update:
I have accepted JPP's answer below, but he's correct this is far too expensive a process for a routine operation. So I need to change my approach. The manager class will instead maintain a static list of service clases. While not ideal from a development perspective, the run-time speed gains seem well worth it.
Upvotes: 6
Views: 1792
Reputation: 59994
Currently (2.8.1/2.9), Scala has no specific reflection/introspection system, but you're free to use Java's. In this particular case, you can port one of the techniques used on the Java side to list all classes in a package, e.g. as shown here (be sure to pick the version in the comments):
http://snippets.dzone.com/posts/show/4831
This technique actually doesn't use Java reflection to find about the classes; what it basically does instead is go through all resources available to the ClassLoader and check which ones are .class
files.
I see a few caveats though:
Upvotes: 4