循环遍历 Scala 包中的每个类
有没有办法可以“循环”Scala 中指定包中的类集?
该用例正在管理一组继承自 BaseService 特征的服务,这些服务通过提供的名称公开给 REST API。 Manager 类需要能够提供服务列表并验证所提供的服务是否存在,如果存在,则实例化它并执行重载函数。
我的想法类似于这样的伪代码:
for ( clazz <- com.demo.pkg ) {
val service = Class.forName(clazz).newInstance
registerService( service )
}
同名对象上的静态方法提供服务名称和描述可能比实例化更好。
在 Python 中,由于 dir(),这很简单;在 PHP 中,由于类加载器函数,这相当容易,但我是 Scala 的新手。
另外,我知道我可能会错误地处理这个问题,并欢迎反馈。
更新:
我已接受 JPP 下面的回答,但他是正确的,对于常规操作来说,这是一个过于昂贵的过程。所以我需要改变我的方法。管理器类将维护服务类的静态列表。虽然从开发的角度来看并不理想,但运行时速度的提升似乎是值得的。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
目前(2.8.1/2.9),Scala 没有特定的反射/内省系统,但您可以自由使用 Java 的。在这种特殊情况下,您可以移植 Java 端使用的一种技术来列出包中的所有类,例如如下所示(请务必在注释中选择版本):
http://snippets.dzone.com/posts/show/4831
这种技术实际上并不使用 Java 反射来查找课程;它基本上所做的是遍历类加载器可用的所有资源并检查哪些是
.class
文件。不过,我看到了一些警告:
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: