Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you get a class name as a constant for scala annotations?

I have an annotation which requires a String describing a class name, eg com.package.MyClass.

I can pass it as a string but would like it to reference the class itself for compilation/refactoring.

However I cannot use MyClass.getName. or classOf[MyClass].toString because it is not a constant:

Compilation error[annotation argument needs to be a constant

Is there a way to get a const reference to a classes name? Or another way to reference the class names as a string in annotations?

like image 922
Jethro Avatar asked Sep 27 '19 11:09

Jethro


People also ask

What is constant in Scala?

Constants, Values and Variables Similar to Java's static final members, if the member is final, immutable and it belongs to a package object or an object, it may be considered a constant: object Container { val MyConstant = ... } The value: Pi in scala. math package is another example of such a constant.

Does order of annotations matter?

Considering annotations that are processed by annotation processors, it was already stated in the other answers that it more depends on the order in which the processors run. However, the processors have access to the AST, which allows them to determine the order of annotations in the source code.

Does scala have annotations?

In Scala, declarations can be annotated using subtypes of scala. annotation. Annotation . Furthermore, since Scala integrates with Java's annotation system, it's possible to work with annotations produced by a standard Java compiler.


1 Answers

You can't use classOf because it runs on runtime and Java annotations requires constants as arguments. Instead, you could capture the name of your class during compile time using macros.

I would recommend you to use some library which can do that, for example NameOf.

Add dependency on your build.sbt:

libraryDependencies += "com.github.dwickern" %% "scala-nameof" % "1.0.3" % "provided"

Then you can use it like:

import com.github.dwickern.macros.NameOf._

@ApiImplicitParams(Array[ApiImplicitParam](
   new ApiImplicitParam(
     name="Something",
     dataType= qualifiedNameOfType[com.package.MyClass])
   )
)
like image 200
Krzysztof Atłasik Avatar answered Sep 28 '22 05:09

Krzysztof Atłasik