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

前端 未结 7 1120
旧时难觅i
旧时难觅i 2020-12-14 22:50

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.

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-14 23:33

    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.

提交回复
热议问题