开发者

Looping through each class in a package in Scala

开发者 https://www.devze.com 2023-02-24 12:39 出处:网络
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

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 chang开发者_StackOverflowe 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.


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:

  • As with Java, you can only see classes visible to a certain classloader (this may be a problem, e.g. in OSGi applications)
  • The operation is expensive enough in Java, and even more so in Scala, as scalac generates a lot of additional classes for all the anonymous functions generated in your code, which can be a significant number owing to methods like filter, map, flatMap, etc. You may try to filter them out based on their name.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号