开发者

What is the difference between Groovy's AnnotationNode and Java's annotation?

I've written a library in which I do some introspection on Java fields to have their annotation list (and more specifically to see if they have one or more specific annotati开发者_Go百科ons (like - say, @Id, @Child, @Parent). Here is an example of the kind of code I use :

    @Override
    public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
        return mapped.getAnnotation(annotationClass);
    }

Where mapped is a Java Field (and as a consequence has a getAnnotation(Annotation) method). I want to port this method to Groovy.

I've already have understood that using Groovy, I have to replace my Fields (or bean properties) by MetaProperties. however, I face an issue considering the use of these annotations, as it seems that groovy handles them very differently from Java.

So, is it possible to consider a migration path from Java annotations to Groovy AnnotationNode, or will i have to create an abstraction over those concepts ?


I'm not sure about AnnotationNode. Based on the package it's in, I'd assume it has to do with AST Transformations.

In any case, your code should work in Groovy the same as Java. I use JPA in Groovy and have accessed the annotations via Java reflection. If you're having a specific problem, please provide more detail.

You seem confused about "fields" vs "metaProperties". You don't change your fields into metaProperties. Your fields become metaProperties. In other words, a field on a Groovy class is a bean property by default ( you get the getter/setter for free). You can access the properties dynamically using Groovy but they are still Field's in the bytecode.

Below is a little Groovy script demonstrating accessing a bean property and getting it's annotation.

import java.lang.reflect.*

class Person {

  @Deprecated
  String name

}

def me = new Person(name:'dave')

assert me.name == 'dave'
assert me.'name' == 'dave'
assert me.getName() == 'dave'

assert Person.class.getDeclaredField('name') instanceof Field
assert Person.class.getDeclaredField('name').getAnnotations()
assert Person.class.getDeclaredField('name').getAnnotation(Deprecated.class) 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜