Intersection of each class in a package in Scala

Is there a way that I can “skip” a set of classes in a specified package in Scala?

A use case is to manage a set of services inherited from the BaseService attribute that receive an accessible name for the REST API. The Manager class should be able to provide a list of services, and also check whether the provided service exists, and, if so, create an instance to perform the overloaded function.

My thought is something like this pseudocode:

for ( clazz <- com.demo.pkg ) { val service = Class.forName(clazz).newInstance registerService( service ) } 

Instead of instantiating, static methods on the object of the same name to provide the name and description of the service might be better.

In Python, this is trivial because of dir () and in PHP it is pretty simple because of the functions of the class loader, but I'm new to Scala.

In addition, I understand that I can approach this incorrectly and welcome feedback.

Update:

I accepted the JPP answer below, but it will fix it too expensive - a process for a normal operation. Therefore, I need to change my approach. Instead, the manager class will contain a static list of service clusters. Although this is not ideal from a developmental point of view, gaining speed while working seems to be worth it.

+6
source share
1 answer

Currently (2.8.1 / 2.9), Scala does not have a specific reflection / introspection system, but you can use Java. In this particular case, you can transfer one of the methods used on the Java side to display all the classes in the package, for example. as shown here (be sure to select the version in the comments):

http://snippets.dzone.com/posts/show/4831

This method does not actually use Java reflection to search for classes; instead, it executes all available ClassLoader resources and checks which ones are .class files.

I see a few warnings:

  • As in Java, you can only see classes that are visible for a particular class loader (this can be a problem, for example, in OSGi applications).
  • The operation is quite expensive in Java, and even more so in Scala, since scalac generates many additional classes for all anonymous functions generated in your code, which can be a significant number thanks to methods such as filter, map, flatMap, etc. You can try to filter them based on their name.
+4
source

Source: https://habr.com/ru/post/885787/


All Articles