users@jaxb.java.net

Re: XJC: get the Annotation-Information of a field

From: Wolfgang Laun <wolfgang.laun_at_gmail.com>
Date: Fri, 27 Nov 2009 10:11:33 +0100

On Fri, Nov 27, 2009 at 8:25 AM, Florian Bachmann
<f.bachmann_at_micromata.de>wrote:

> Dear XJC-Users,
> how I can find out, how an field is annotated?
>
> Suppose I have a class with two fields:
> SupposedClass {
> @XmlElement(name = "AnElement")
> protected AnElement anElement;
> @XmlAttribute(name = "attribute")
> protected AnAttribute attribute;
> }
>
> How can I find out, if an field is an XmlElement or an XmlAttribute and
> which name it uses?
>
>
See the code below. - You may want to catch the "##default" and replace it
with the field's own name.
-W

import java.util.*;
import java.lang.reflect.*;
import java.lang.annotation.*;
import javax.xml.bind.annotation.*;

public class AnnotationReader {

    private final Class clazz;

    public AnnotationReader( Class clazz ){
        this.clazz = clazz;
    }

    private List<Field> getFieldsWith( Class annotation ){
        Field[] fields = clazz.getDeclaredFields();
        List<Field> fList = new ArrayList<Field>();
        for( Field f: fields ){
            Annotation[] annos = f.getDeclaredAnnotations();
            for( Annotation a: annos ){
                if( annotation.isInstance( a ) ){
                    fList.add( f );
                    break;
                }
            }
        }
        return fList;
    }

    public List<Field> getElementFields(){
        return getFieldsWith( XmlElement.class );
    }

    public List<Field> getAttributeFields(){
        return getFieldsWith( XmlAttribute.class );
    }

    public Map<String,String> getSchemaNames() throws Exception {
        Field[] fields = clazz.getDeclaredFields();
        Map<String,String> field2tag = new HashMap<String,String>();
        for( Field f: fields ){
            Annotation[] annos = f.getDeclaredAnnotations();
            for( Annotation a: annos ){
                if( a instanceof XmlElement ||
                    a instanceof XmlAttribute ){
                    Class annoClass = a.annotationType();
                    String tName = (String)annoClass.getMethod( "name"
).invoke( a );
                    field2tag.put( f.getName(), tName );
                }
            }
        }
        return field2tag;
    }
}