Search code examples
javainterfaceannotations

How to make automatic setter and getter using annotation in java?


It's very tough to add getter and setter method for all objects is there any easy way to do that? can we create an interface or annotation for that?

private String name; public void setName(String name) {this.name = name;} public String getName() {return name;}

I wish something like @GetterSetter private String name;

I know that Eclipse and IDEA will generate easily what I want my code looks clean i don't want to make my number of lines x*5 more.


Solution

  • If you don't want to use inteliJ special features or external libraries you must write your own annotation's processor which will process example setter and getter's annotations(for example: @Get, @Set).

    But when defining the two annotations you must remember about the special type of metaannotation: @Retention(RetentionPolicy.RUNTIME)

    because w/o this RetentionPolicy your getter's and setter's annotation won't be available in final program !

    Annotation processor you write using reflection on your two annotations.

    If you don't want to write this processor you can use even apt from default JDK.

    Cheers, gjm