Monday, 27 May 2013

Scala Code snippet: Look for methods with Java annotations

Hi, This is a small code snippet I am using to look for methods with Java annotations. First the Java annotation:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface EnableForMonitoring {
}
Second a class that would have some methods annotated with @EnableForMonitoring:
class C {
  def m1 = {}
  @EnableForMonitoring def m2(i: Int) = {}
  def m3(s: String): Int = -1
}
Finally, the code snippet to look up those methods:
val c = new C

val jmxannotation = ru.typeOf[EnableForMonitoring]    
val m = runtimeMirror(getClass.getClassLoader)
val mSymbol = m.classSymbol(c.getClass)
val mType = mSymbol.selfType

mType.declarations.foreach(symbol => {
  val sa = symbol.annotations.find(a => a.tpe == jmxannotation)
  sa match {
    case Some(_) => info(s"(A) For $symbol, annotations: $sa") 
    case None =>
  }
})
Voila

No comments:

Blog Archive