questions on annotation + class member order

I would like to do something like this:

public class Foobar {
   @Tag final private int foo;
   @Tag final private int bar;
   @Tag final private int baz;
   @Tag final private int quux;

   static private final TagValidator validator = 
      TagValidator.autoGenerate(Foobar.class);

   public Foobar(Something something)
   {
       validator.validate(something);
       this.foo = something.method1();
       this.bar = something.anotherMethod();
       this.baz = something.someOtherMethod();
       this.quux = something.yetAnotherMethod();
   }
   ... other methods ...
}

where TagValidator.autoGenerate() uses reflection + annotation parsing to get all the members of my Foobar class that have been tagged with @Tag and do some grungy laborious boring stuff which I’m going to need to do for several classes.

My question is, is it going to see these members in the order they are declared? I agree it would be safer to do this:

public class Foobar {
   @Tag(0) final private int foo;
   @Tag(1) final private int bar;
   @Tag(2) final private int baz;
   @Tag(3) final private int quux;

   ...
}

but I’m feeling lazy 🙂

Also, is it possible to have a class and an annotation with the same name?

Answer

To quote the JavaDocs on both Class.getDeclaredFields() and Class.getFields()

The elements in the array returned are not sorted and are not in any particular order.

From a maintainability perspective if the order is important include it in your annotation or better still don’t rely on the order.

Yes, it is possible to for a class and annotation to have the same name providing they are in a different package. Basically the same rules apply as classes and interfaces.

Leave a Reply

Your email address will not be published. Required fields are marked *