vendredi 19 mai 2017

Setting class of an Scala object to a field of a Java annotation

I have a Java annotation like the following:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ConvertWith {
  Class<? extends Converter> converterClass();
}

And I have several converter objects written in Scala. For example, IntConverter is shown below:

object IntConverter extends Converter {
  def convert(str: String) = str.toInt
}

I want to use these objects like the following to associate them with fields:

class SampleAction {
  @ConvertWith(converterClass = classOf[IntConverter])
  val x: Int = 0
}

However, Scala cannot find the converter class because scalac compiles objects differently.

I have also tried the following ways but none of them worked:

// error: class type required but IntConverter.type found
@ConvertWith(converterClass = classOf[IntConverter.type])

// error: annotation argument needs to be a constant...
@ConvertWith(converterClass = IntConverter.getClass)

Is there a way to do this? Do you have any ideas?

Thanks in advance.





Aucun commentaire:

Enregistrer un commentaire