Is there a way to use annotations in Java to replace accessors?

Getters/Setters: Yes, it is possible. The Project Lombok (http://projectlombok.org/index.html) defines annotations for generating getters/setters and more.

So for example

@lombok.Data;
public class Person {
   private final String name;
   private int age;
}

Will generate getName (no setter since the variable is final) and getAge/setAge. It will also generate equals, hashCode, toString and aconstructor initializing the required fields (name in this case). Adding @AllArgsConstructor would generate a constructor initializing both fields. Using @Value instead of @Data will make the objects immutable.

There are other annotations and parameters giving you control over access rights (should your getter be protected or public), names (getName() or name()?), etc. And there is more. For example, I really like the annotations for builders and extension methods.

Lombok is very easy to use:

  • Just download the jar and use the annotations, the automatically generated getter/setters can be used in your code without actually being spelled out.
  • The annotations are used only during compilation not during runtime, so you don't distribute lombok with your jar's.
  • Most IDE's support this, so that you see the getter/setter in code completion, navigation, etc. In Netbeans this works out of the box. In IntelliJ IDEA use the Lombok plugin.

NotNull: This is supported by findbugs and IDEA IDE, maybe others


Annotation processing occurs on the abstract syntax tree. This is a structure that the parser creates and the compiler manipulates.

The current specification (link to come) says that annotation processors cannot alter the abstract syntax tree. One of the consequences of this is that it is not suitable to do code generation.

If you'd like this sort of functionality, then have a look at XDoclet. This should give you the code generation preprocessing I think you are looking for.

For your @NonNull example, JSR-305 is a set of annotations to enhance software defect detection, and includes @NonNull and @CheckForNull and a host of others.

Edit: Project Lombok solves exactly the problem of getter and setter generation.