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.
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.
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