mardi 24 août 2021

Get class of Scala object for annotation

I have a use case where I need to do some Java reflection on some Scala objects (don't even ask). Anyway, I sometimes need to add these objects to an annotation, in Scala.

Here's my (java) annotation:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
   Class<?>[] value();
}

And let's say this is my Scala object:

object Foo{}

In Java, I can reference Foo using my above annotation like this:

@MyAnnotation(Foo.class)
class SomeClass{}

In Scala, however, I don't see how I can get a type literal from an Object:

@MyAnnotation(Array(classOf[Foo]))
class SomeClass{}

This fails, with error message:

not found: type Foo

Is there any way I can reference my Foo object type in a Java annotation? Note that I can't use Foo.getClass, because that's a method call, not a constant.





Aucun commentaire:

Enregistrer un commentaire