简体   繁体   English

如何让java方法注释在scala中工作

[英]How do you get java method annotations to work in scala

I've got two projects, a scala project and a java project. 我有两个项目,一个scala项目和一个java项目。 My scala project references the java project in the build path. 我的scala项目引用了构建路径中的java项目。 In my java project, i'm declaring the following annotation: 在我的java项目中,我正在声明以下注释:

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

In my scala project, I'm annotating some methods. 在我的scala项目中,我正在注释一些方法。 Ie

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. 不幸的是, annotations总是一个空数组。 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. 编辑最初,我用myAnnotation两次注释myMethod,这是不正确的,正如有人指出的那样。 It turns out this wasn't the problem. 事实证明这不是问题。 I'm still getting an empty array for annotations . 我仍然得到一个空数组用于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 我尝试了你的代码,问题是你使用@MyAnnotation两次myMethod,它应该引发AnnotationFormatError:类的重复注释

When i change to use it once, the reflection just retrieves the annotions. 当我改为使用它一次时,反射只是检索注释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM