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?
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.
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.
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.
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])
)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With