Skip to content
Anjunar/ DOCS

Companions and class path

Two helpers around types: the companion object of a Scala class, and an index of annotations over a package.

Companions

From a class to its object

companionClass finds the class Name$, companionInstance its MODULE$ instance, checked against the expected type. Both return null when there is none.

scala
class Service object Service val companionClass = TypeResolver.companionClass(classOf[Service]) val companion = TypeResolver.companionInstance[Service.type](classOf[Service]) println(companionClass.getName) // Service$ println(companion eq Service) // true

json-mapper finds an entity's schema this way: the companion that implements SchemaProvider. Because companionInstance checks the type, a companion of another kind comes back as null instead of failing later.

scala
val provider = TypeResolver.companionInstance[SchemaProvider[?]](classOf[Article]) if provider != null then println(provider.schema.properties.keys.mkString(", "))
Class path

An annotation index

process loads every class below a package prefix and indexes the annotations on classes, constructors, their parameters, fields and methods. findAnnotation returns each annotation with the element that carries it.

scala
import com.anjunar.scala.universe.ClassPathResolver val classes = ClassPathResolver.process("com.example", Thread.currentThread().getContextClassLoader) ClassPathResolver.findAnnotation(classOf[jakarta.inject.Singleton]) .foreach(found => println(found.target))
In a CDI container

ClassPathResolver is also a CDI extension. Registered in META-INF/services, it collects every type the container discovers and builds the same index after deployment.

text
# META-INF/services/jakarta.enterprise.inject.spi.Extension com.anjunar.scala.universe.ClassPathResolver
Index first

findAnnotation throws NoSuchElementException for an annotation that was never indexed. Run process, or let the CDI extension run, before looking anything up.