Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get java method annotations to work in scala

I've got two projects, a scala project and a java project. My scala project references the java project in the build path. In my java project, i'm declaring the following annotation:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    public String Name();
}

In my scala project, I'm annotating some methods. I.e.

class MyClass {
    ...
    @MyAnnotation(Name="Blah")
    def myMethod() {
        ...
    }
}

In another file somewhere, i'm trying to pull out the annotations.

var methods = myClassInstance.getClass().getDeclaredMethods()
var myMethod : Method = null
for (method <- methods) {
  if (method.getName().equals("myMethod")) {
    myMethod = method
  }
}
var annotations = myMethod.getDeclaredAnnotations()

Unfortunately, annotations is always an empty array. Am I doing something fundamentally wrong or am I just missing something minor? Thanks!

EDIT Originally, I was annotating myMethod with myAnnotation twice, which is incorrect as someone pointed out. It turns out this wasn't the problem. I'm still getting an empty array for annotations. No exception is being thrown.

like image 764
Jordan Avatar asked Dec 19 '12 02:12

Jordan


1 Answers

I tried your code, the problem is that your use @MyAnnotation twice for myMethod, which should raise AnnotationFormatError: Duplicate annotation for class

When i change to use it once, the reflection just retrieves the annotions.

like image 122
Qiang Jin Avatar answered Sep 23 '22 14:09

Qiang Jin