Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm a little new to the Java 5 annotations and I'm curious if either of these are possible:

This annotation would generate a simple getter and setter for you.

@attribute
private String var = "";

The @NotNull annotation indicates that a variable connot be null so you don't have to write that boilerplate code every time.

/*
 * @param s @NotNull
 */
public void setString(String s){
    ...
}

Will either of these work? They seem like the first things I would write annotations for if I could. Since I don't see much about these when I read the docs I'm assuming that it's not really what annotations are about. Any direction here would be appreciated.

like image 849
Jason Tholstrup Avatar asked Dec 08 '08 00:12

Jason Tholstrup


People also ask

Do Java annotations do anything?

Java annotations are used to provide meta data for your Java code. Being meta data, Java annotations do not directly affect the execution of your code, although some types of annotations can actually be used for that purpose.

Are getters and accessors the same?

Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Given this, getters and setters are also known as accessors and mutators, respectively.

How do you bypass Lombok getter?

From Lombok documentation: You can always manually disable getter/setter generation for any field by using the special AccessLevel. NONE access level. This lets you override the behaviour of a @Getter, @Setter or @Data annotation on a class.

Can we annotate interface in Java?

Annotation is defined like a ordinary Java interface, but with an '@' preceding the interface keyword (i.e., @interface ). You can declare methods inside an annotation definition (just like declaring abstract method inside an interface). These methods are called elements instead.


1 Answers

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.

like image 172
jamesh Avatar answered Nov 12 '22 17:11

jamesh